1

I've read that arrays and objects are "being passed by reference". But I've encountered behavior, which confuses me.

In this piece of code, everything works as I would expect

let first = [1, 2, 3, 4, 5];
let second = first;
first.push(10);
console.log(first); //[ 1, 2, 3, 4, 5, 10 ]
console.log(second); //[ 1, 2, 3, 4, 5, 10 ]

I have troubles understanding the following one

let third = [1, 2, 3, 4, 5];
let forth = third;
third = [11, 12];
console.log(third); //[ 11, 12 ]
console.log(forth); //[ 1, 2, 3, 4, 5 ]

I would expect both variables to be equal, but it works as I'm operating primitives, not an array.

  • 5
    The variables aren't linked by reference. The variables *hold* a reference to the object. If you assign something else to one of the variables, then it will hold a reference to a different object. Doesn't affect the reference the other variable holds. – deceze Jul 08 '19 at 08:50
  • 1
    The difference is in the first round you’re mutating the object referenced by both variables, but in the second you’re simply _reassigning_ one, that is assigning it a new reference. The old reference still points to the original object. Probably bad analogy: if you update your home address on one website it has no effect on other websites or the house itself. But if you build an extension on the house, the house is changed, no matter who looks at it. – Christopher Jul 08 '19 at 08:53
  • i.e. — `let third = [1, 2, 3, 4, 5];` sets the value of `third` to be a reference to an array. `let forth = third;` copies that value, so the value of `fourth` is a reference to the **same** array. `third = [11, 12];` assigns a reference to a **new** array to `third`. This doesn't touch `fourth` because it holds a reference to the first array, it doesn't hold a reference to the variable `third`. – Quentin Jul 08 '19 at 08:54

0 Answers0