1

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?

1
  • That’s not a question about arrays, but about variables. When you write arr1 = [2, 3, 4];, a new array [2, 3, 4] is created and assigned to arr1. That new array has nothing to do with arr2 or the other array anymore. Commented Aug 4, 2018 at 23:58

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is this due to immutability nature?
No...has nothing to do with immutability. Simply a value change. The new value points to a completely different object(array)
@sv123 No, arrays are mutable. It's just the fact you're completely reassigning to a whole new array and thus a whole new reference (to array in memory)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.