Javascript By Reference vs By Value

By on

Sometimes Javascript makes me want to kick little kittens. This time it’s because there is no built-in way to pass objects by value. First a little guide regarding Javascript and by reference vs by value:

Why this matters

Every time you pass an object to a function and change it, the original will also be modified. This is understandable behavior seeing as the object could be quite large and therefore memory-intensive if were to be copied at will. So how can you pass an object by value? Javascript: The Definitive Guide gives us a clue (emphasis added):

A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside of the function.

Basically you have to create a new object and copy each of the original properties to it. I have three things to say about this:

  1. It’s stupid, why can’t there just be a way to specify by value like any other language?
  2. There’s no way around this limitation. It’s built into Javascript on purpose by people much smarter than me.
  3. jQuery can help

jQuery to the rescue

jQuery has a nice method that can be used to copy one object to another: jQuery.extend(). Just add this line to the top of your function when you do not intend to modify the original:

var newObj = jQuery.extend({}, oldObj);

Make sure to check out the documentation for more information if you’ve got a complex object. Also, if you’re looking for a non-jQuery solution, How to copy arrays and objects in Javascript provides true object cloning (not copying) which may make it more efficient.

Update: Fixed formatting and dead link