1

I tried the following code on my chrome developer console

array = [1,2,3]
[1, 2, 3]
copyarray = array
[1, 2, 3]
copyarray = [1]
[1]
array
[1, 2, 3]
copyarray = array 
[1, 2, 3]
copyarray
[1, 2, 3]
copyarray.pop()
3
copyarray
[1, 2]
array
[1, 2]
copyarray+''
"1,2"
copyarray = copyarray +''
"1,2"
array
[1, 2]

Can anyone tell the reason why value of "array" changes when i use use some Array methods(like pop splice etc.) on "copyarray" variable?

4 Answers 4

3

Because when you assign the value of one variable to the other, you're making a copy of a reference to the (single) array object. JavaScript does not provide a primitive operation for making a complete copy of an object. The closest is probably the .slice() method on arrays:

var copyarray = array.slice(0);

Now there are two arrays, and modifications to one won't affect the other.

2

Javascript assigns objects by reference, not by value. You have two names referring to the same object.

It sounds like you want to clone your array.

1
  • Please include the relevant code in your answer, so that it doesn't become useless if (or when) the link rots away.
    – Aran-Fey
    Commented Oct 3, 2022 at 13:38
1

Becuase these are references. You can however do this, which will clone the array.

var copyarray = array.slice(0);

instead of:

copyarray = array 

Another option is to create a prototype.

Array.prototype.clone = function() {
    return this.slice(0);
};

var copyarray = array.clone();
1
  • But why it is not true in case of a string like var str1 = 'jeswin '; str2 = str1; str2.trim() str1 now remains unchanged
    – jsHero
    Commented Jan 27, 2014 at 4:29
0

well copyarray and array both point to the same array object, and on the other hand methods pop and splice (not slice) modify the array at hand directly. So if you apply any of these methods on an instance, that instance will be modified and as a result all the variables pointing to that array will be pointing to that modified version of that array.

Not the answer you're looking for? Browse other questions tagged or ask your own question.