In Javascript is not always clear wether an assignment of a variable or object is being passed by reference or by value.

Variables

When a variable gets assigned with a primitive type like a number or a string the value is passed in by value:

var number = 1;
var secondNumber = number;

secondNumber = 20;
console.log(number); // prints out 1

The same does not happen when creating an object from another object, instead of the object being copied to a new object, a pointer of the object gets copied to the new object, kind of confusing, let me try to explain with an example...

var obj = { number: 1 }; // obj.number prints 1
var secondObj = obj; // assigned from previous object

secondObj.number = 20; // update value in second object

// try to print the number attribute in the first object
console.log(obj.number); // prints out 20!! WHAATT!!

As you can see in the example when trying to edit the number attribute of the second object, we are actually updating both objects, because the second one has a pointer to the first object. Even though this seems as a really weird "feature" it actually comes in handy sometimes.

One of this cases is when storing a reference to a jQuery object so we don't have to fetch it each time we are going to use it.

Function Arguments

We have a pretty similar case when passing arguments to a function in Javascript.

If the argument is a variable holding a number or string, the variable is passes by value, and therefore any changes that we try to apply to it will only be made inside that scope.

var number = 1;
function foo(num){
    num = 2;
}

foo(number);
console.log(number) // will print 1

With objects is different, when passing an object as an argument to a function, the object gets passed by reference, and every change that we try to make to the object will be made to all the objects that reference the same point in memory.

var obj = { number: 1 };
function foo(obj){
    obj.number = 100;
}

foo(obj);
console.log(obj.number) // will print 100!!

Hope this helps in your journey to become a better programmer, it definitely helped me when I found out.

Happy Coding! :)


Comments? Something wrong in the post? or just want to contact me? Send me a tweet to @gpopoteur on twitter.