Manipulating Copies of JavaScript Objects with KnockoutJS

I recently ran into an issue when trying to change properties of what I thought was a copy of a JavaScript object.  I made all of the new object’s properties observable, and then tried changing the value of one of the properties in the new object. It turns out that this was also changing the same property in the original object.  This is all because JavaScript objects are assigned by reference, not value! For example:

var x = y;

In the example above, the object x is not a copy of y. It is a reference to y! So how does this relate to knockout?

In my project, we have data from the server given to the client in JSON format.  It is then given to the client-side viewModel, all non-observable.  In order to take the data from the server and make the data we need to be observable, we use a method to set all of an object’s properties to be observable.  This stomps over the original object, which is okay because we don’t ever need the original non-observable object that came from the server.  If, however, I need to clone the object’s data and manipulate properties on the clone, while keeping the original, I’ve found the easiest way is to use the jQuery extend() method.  You can specify whether or not to make a deep (recursive) copy, and even merge 2 objects as well.  The following example makes use of this method:

Notice in the results that the original object has “Not John” as the First name, since it was inadvertently changed on its reference. The object changed using the extend method did not affect the original!


Can You Help Me Name Some Variables?

One of the seemingly simplest tasks in programming is sometimes one of the hardest: naming variables.  One day, a coworker of mine was asked by numerous people throughout the day to help come up with meaningful variable and function names that applied to their specific situations.  By the end of the day, she was mentally exhausted from the all of the thinking and internal deliberation involved.
This mental struggle seems to be present when naming any variable, function, class, property, enumeration, or namespace. It’s always difficult to come up with a name that
  1. Represents the data accurately
  2. Is verbose enough but still concise
  3. Makes sense to you
  4. Makes sense to any other team members that will come across your code in the future

It’s important that all of these criteria are met if you have any hopes of maintaining the software moving forward.

This struggle of my coworker that day inspired me to write a song about the whole process of naming variables while writing code.  The song portrays a developer (myself) trying and trying to write code, but I need help naming variables. With none of my coworkers able to help and getting caught up in meetings, it seems like I can never make any progress! It’s just one of those days…

You can find the song below: