0

I have these two arrays:

    let num1 = [[1]];
    const num2 = [2, [3]];

I concat these two and create new array:

    const numbers = num1.concat(num2);
    console.log(numbers);
    // results in [[1], 2, [3]]

Now I push a new value to num1:

    num1[0].push(4);
    console.log(numbers);
    // results in [[1, 4], 2, [3]]

But if I write:

    num1[0] = [1, 4, 5];
    console.log(numbers);
    // results in [[1], 2, [3]]

Why reassigning vale to num1 does not reflect change in numbers array but push method does?

Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 1
    https://stackoverflow.com/questions/13266616/primitive-value-vs-reference-value – Rocky Sims Feb 02 '20 at 17:24
  • 1
    Almost sure there are 92345623 dupes for this, but still waiting for a proper one. While the above is related, it doesn't really tackle the issue head on. – ASDFGerte Feb 02 '20 at 17:28

2 Answers2

2

num1[0] starts out with a value that is a reference to an array [1]

numbers copies that value, so has a reference to the same array.

num1[0].push(4); modifies that array (which you have two references to)

num1[0] = [1, 4, 5]; modifies the value of num1[0] replacing the reference to the original array with a reference to a brand new array. numbers still contains a reference to the original array.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

That's because arrays are objects in Javascript. And objects in JavaScript are always references, so when you push an array to another array, you are actually pushing a reference, not a value.

When you concatenate two arrays, it will copy the values (or references) to a new array.

When you set the value of index 0, you are actually replacing that reference, but the old reference still exists in the concatenated array.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59