0

Suppose you have the following code:

var array = [1];
var array2 = array;

array2.push(2);

alert(array);

This will alert "1,2", even though I clearly declared array as [1], and then did no changes to it. It's like array and array2 gets connected, and every change I do to array2 affects array. I simply want to declare array2 with the same value as array, not connect them.

Why does this happen and how to prevent it?

Thanks in advance!

jsFiddle

Istlemin
  • 131
  • 2
  • 11

5 Answers5

1

The problem is, that array2 is pointing on array.

what you want is:

var array2 = array.slice(0);

This really creates a copy of "array" and does not let the variable array2 point on "array".

jvecsei
  • 1,936
  • 2
  • 17
  • 24
1

It's because arrays and objects in JS are "passed by reference" (actually a copy of reference), not value (as it happens with primitives). There are many ways to do it, one of them being concatting an empty array:

var array = [1];
var array2 = array.concat([]);

array2.push(2);

alert(array);    // 1
alert(array2);   // 1,2

See some nice answers here: Does Javascript pass by reference?

Community
  • 1
  • 1
Shomz
  • 37,421
  • 4
  • 57
  • 85
1

Befor all , in Javascript an array is an Object so the array variable is pointing to an in array (that you created [1]) that has an adresse in the memory (for example @1234abc). So the variable array it self is a pointer that points to an array.

You did var array2 = array so array2 will point to the same adress in the memory (to the same object).

In other words, array2 is array they are pointing to the same object.

To get what you want, you have to create a new array and assign the same values of array1, this is called cloning. You can do it with this trick var array2 = array.slice(0);

Sn0opr
  • 1,016
  • 2
  • 12
  • 38
0

array2 is a reference to the original array, so if you modify it, the original will change too.

You´ll have to set array2's value to array.slice(), which clones the original and gives you a new reference.

Emile Pels
  • 3,837
  • 1
  • 15
  • 23
0

It is because of concept Pass by reference. Internally both the variables are pointing to same memory location. So, when you change one variable that will effect other variables as well. Try slice() method if you intend to copy only values but not reference as it is. :)

Abhishek
  • 6,912
  • 14
  • 59
  • 85