Why does changing an Array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

Your comparison with the number example is not correct btw. You assign a new value to copyOfMyNumber. If you assign a new value to copyOfMyArray it will not change myArray either.

You can create a copy of an array using slice [docs]:

var copyOfMyArray = myArray.slice(0);

But note that this only returns a shallow copy, i.e. objects inside the array will not be cloned.

Leave a Comment