I've written the following JavaScript:
var myArray = ['a', 'b', 'c'];
var copyOfMyArray = myArray;
copyOfMyArray.splice(0, 1);
alert(myArray); // alerts ['b','c']
alert(copyOfMyArray); // alerts ['b','c']
var myNumber = 5;
var copyOfMyNumber = myNumber;
copyOfMyNumber = copyOfMyNumber - 1;
alert(myNumber); // alerts 5
alert(copyOfMyNumber); // alerts 4
This code declares a variable myArray
and sets it to an array value. It then declares a second variable copyOfMyArray
and sets it to myArray
.
It performs an operation on copyOfMyArray
and then alerts both myArray
and copyOfMyArray
. Somehow, when I perform an operation on copyOfMyArray
, it appears that the same operation is performed on myArray
.
The code then does the same thing with a number value: It declares a variable myNumber
and sets it to a number value. It then declares a second variable copyOfMyNumber
and sets it to myNumber
. It performs an operation on copyOfMyNumber
and then alerts both myNumber
and copyOfMyNumber
. Here, I get the expected behavior: different values for myNumber
and copyOfMyNumber
.
What is the difference between an array and a number in JavaScript that it seems changing an array changes the value of a copy of the array, where as changing a number does not change the value of a copy of the number?
I'm guessing that for some reason, the array is referred to by reference and the number by value, but why? How can I know what behavior to expect with other objects?