-4

Let me explain. I have the following piece of code :

let a = [1, 2, 3];
let b = a;
b.splice(2, 1);
console.log("a: " + a);
console.log("b: " + b);

I would have expected to get something like :

a = [1, 2, 3];
b = [1, 2];

However, after running the code, it turns out both "a" and "b" equal [1, 2]. I am really confused, since "b" should only have been assigned a copy of "a", instead of acting as some sort of a pointer to "a". I wonder if it is because JS handles arrays (objects) differently of if it is something specific to the splice function. I would also like to know how you would bypass that odd behavior.

Thanks for your time.

John Krakov
  • 355
  • 1
  • 8

1 Answers1

2

In the first line you are creating the array and pointing a variable to that array. In the second line let b = a;, here you are pointing b variable to the a array again.

So both a and b variables will be pointing to the same array. When you do a change to the array, both a and b values will be changed.

Sandeepa
  • 3,457
  • 5
  • 25
  • 41