/ javascript

Javascript objects are passed by reference

This is something to keep in mind, because it is like the very basic foundation of Javascript behavior.

Javascript objects are passed by reference and not copied.
Also, an Array is an Object in Javascript.

What this mean is that you could potentially mutate value of properties that you didn't mean to. Therefore, you may have heard of the term Immutability.

Below is an example:

var a = 1;

var b = a;

b += 1;
console.log(a,b);

var c = [1];
var d = c;

d[0] = 2;
console.log(c,d); // c is mutated

var e = {0:1};
var f = e;

f[0] = 2;
console.log(e, f); // e is mutated

JS Bin on jsbin.com

Observe that the values c, an Array and e and Object has been mutated by their referenced copy, d and f respectively.

Javascript objects are passed by reference
Share this