0

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,

1
  • 1
    x = [1,2,3]; y = x; y[0] = 7; console.log(x) will output 7,2,3. arrays in JS are objects, and when you copy an object via newobj = origobj, you're just creating a reference. you need to CLONE the array object to create a truly independent copy.
    – Marc B
    Commented Mar 15, 2013 at 21:56

2 Answers 2

1

Variable assignment in JavaScript never makes copies for non-primitives (everything that isn't a value).

Assignment for all non-values copies references.

1

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
  • I don't remember why exactly, but I think you want that to be arr1.slice(0)
    – rodneyrehm
    Commented Mar 15, 2013 at 21:56
  • You may also want to note that .slice() only creates a shallow copy of the array.
    – rodneyrehm
    Commented Mar 15, 2013 at 21:58

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