0

let a = [1, 2, 3]
let b = a
a = [1, 2]
console.log(b)

I expected that the result will be 1, 2 but it is 1, 2, 3

Bishan
  • 15,211
  • 52
  • 164
  • 258
tunglam24
  • 3
  • 1
  • assigning a new array to `a` won't have an effect on `b`. – Pointy Dec 05 '22 at 04:16
  • Objects are copied by reference, not arrays. – Neha Soni Dec 05 '22 at 04:18
  • 1
    @Neha Soni, this is false. All values in JavaScript are passed by reference. Primitive types are just immutable. So so when you “change” a number or string or Boolean you’re actually reassigning it, and this doesn’t affect the original pointer to the old value. Arrays are objects. Both are mutable. There’s no difference in how they behave in this regard. Same for functions, maps, sets, any non primitive type. – ceckenrode Dec 05 '22 at 04:42

2 Answers2

0
  • Initialize a variable to refer to an array

    let a = [1,2,3];

  • Copy that reference into a new variable

    let b = a;

  • Modify the array using the original reference

    a.splice(2, 1);

  • Display the changed array [1,2] using the new reference

    console.log(b);

Bishan
  • 15,211
  • 52
  • 164
  • 258
0

You’ve changed the pointer of the variable a to a new array, but the old array still exists because b is still pointing to it. All you’ve done is reassign the array that the variable a is now pointing to.

This is working as expected. You’ll get the result you were trying to achieve by mutating the array a is pointing to instead of completely reassigning it. Ie

let a = [1, 2, 3]
        let b = a
        a.pop()
        console.log(b)
ceckenrode
  • 4,543
  • 7
  • 28
  • 48