1

In Javascript, why do the push and unshift functions on a list affect other arrays that the array is assigned to?

For example, if I have an array called list1 and another array called list2 and I assign list1 to list2 as shown below and I push a value into list1, why does list2 also change?

var list1 = [1,2,3];
var list2 = list1;
list1.push(4);
alert(list2);
// Alerts [1,2,3,4]

This is different if I assign an array to list1.

var list1 = [1,2,3];
var list2 = list1;
list1 = [1,2,3,4];
alert(list2);
// Alerts [1,2,3]

Can somebody please help? This is confusing and makes no sense at all.

lw_101
  • 15
  • 1
  • 6
  • 2
    `list1` and `list2` are literally the same array. You've just made two labels for it, rather than copied it in two places. – VLAZ Jan 25 '20 at 19:46
  • 1
    Also relevant: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – VLAZ Jan 25 '20 at 19:47

2 Answers2

2

The reason for that is because Array is not a primitive type. Meaning, if you assign an array to a variable, the variable will be a "pointer" to the Array that is located in the HEAP memory. So if you assign list2 as list, you mean: "Set list2 as the same pointer of list1". In order to make a clone the Array, you can do like so:

var list1 = [1,2,3];
var list2 = Array.from(list1);

list1 = [1,2,3,4];
alert(list2);
// Alerts [1,2,3,4];

The reason you got [1,2,3] in the second example was that you have assigned list1 to a new List, while list1 still points to the original Array.

You can read more about the difference between primitive and reference tyes here - What's the difference between primitive and reference types?

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116
0

This happens because arrays are reference types in JavaScript. The simple solution to this problem is to clone one list into another instead of assigning.

For example, list2 = list1.slice(0);