2

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

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Please include the relevant code in your answer, so that it doesn't become useless if (or when) the link rots away.
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 Comment

But why it is not true in case of a string like var str1 = 'jeswin '; str2 = str1; str2.trim() str1 now remains unchanged
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.