sv123
sv123

Reputation: 21

How do variable assignment with arrays behave in javascript?

I'm trying to understand the exact behavior of arrays in Javascript. I know that they work by reference. But I was confused when I came across this piece of code:

let arr1 = [1,2,3];

let arr2 = arr1;

arr1[2] = 4;

console.log(arr2); // [1,2,4]

arr1 = [2, 3, 4];

console.log(arr2); // [1,2,4] why not [2, 3, 4]

So how exactly do arrays behave in javascript?

Upvotes: 1

Views: 62

Answers (2)

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6501

Think of it like this, a variable is a pointer for an object in memory, now:

  • Line 1: Assingned pointer (arr1) to object [1,2,3]
  • Line 2: Assigned a pointer for a pointer which points to object [1,2,3], this is what is meant by reference.
  • Line 3: changed object [1,2,3]'s last value to 4. At this point arr1 and arr2 still points to this object.
  • Line 4: Assinged the pointer arr1 a NEW object with content [2,3,4]. At this point arr2 points still to the old [1,2,4] object.

Upvotes: 2

charlietfl
charlietfl

Reputation: 171698

When you do let arr2 = arr1; both variables share reference to same actual array.

However if you reassign one of those variables to a different array they no longer share same reference and are completely isolated from each other

Upvotes: 2

Related Questions