When do variables made from arrays act as pointers to the array and when do they act as copies of the array?
For instance if I have an array named Array1
a1=Array1;
is a1 a copy or a pointer to the array.
If I modify a1 will it also modify Array1. By modify I mean change a value, push something into the array, sort, or any other way you could modify an array.
thanks,
2 Answers 2
Variable assignment in JavaScript never makes copies for non-primitives (everything that isn't a value).
Comments
A variable in javascript holds a reference to the array.
If you copy the variable value with arr2 = arr1, you copy the reference to the same array. So any change to arr2 is a change to arr1.
If you want another variable to hold a reference to a copy, so that you may change the second array without changing the first one, use slice :
var arr2 = arr1.slice();
2 Comments
arr1.slice(0).slice() only creates a shallow copy of the array.
x = [1,2,3]; y = x; y[0] = 7; console.log(x)will output7,2,3. arrays in JS are objects, and when you copy an object vianewobj = origobj, you're just creating a reference. you need to CLONE the array object to create a truly independent copy.