0

I need some help understand why a relationship is created between arrays when I replicate an array by reference. Take the following example:

let a = [1,2,3];
let b = a;
b.push(4);
console.log(b); // [1,2,3,4]
console.log(a); // [1,2,3,4]
a === b; // true

For some reason, {a} changes when I modify {b}, when I expected them to be independant arrays.

This kind of relationship is not true for variables, it appears. Take the following example:

let a = 'test';
let b = a;
b = 'test1';
console.log(b); // "test1"
console.log(a); // "test"
a === b; // false

Does anyone know the reasoning behind the behavior for arrays?

  • 1
    This happens because arrays are reference types in JavaScript. That means that if you assign an array to a variable or pass an array to a function, it is the reference to the original array that is copied or passed, not the value of the array. – Sani Huttunen Apr 10 '19 at 14:36
  • In javascript, only **primitives** are "passed by value". Technically, arrays are not exactly passed by reference, however, you may consider that everything that is not a primitive, in javascript, is "passed by reference". – briosheje Apr 10 '19 at 14:36
  • What happens if you replace `a='test'` with `a=[1,2,3]` in the 2nd snippet? – georg Apr 10 '19 at 14:39
  • `a` will be [1,2,3] while `b` will be "test1". `b` will initially point to `a`, then it will be assigned to a new string, hence the reference will be lost, not `a`'s value. – briosheje Apr 10 '19 at 14:44

1 Answers1

0

Arrays are copied by reference so when you write:

let b = a;

You are referencing a in b.

The correct way:

let b = [...a]

or

let b = a.slice(0);
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43