0

In javascript arrays are objects therefore passed by reference. So

var a = ["a"];
var b = a;
console.log(b);
a[0] = "wtv";
console.log(b);

will change b value.

what I don't understand is why

var a = ["a"];
var b = a;
console.log(b);
a = ["wtv"];
console.log(b);

is not changing b value ? what is the reasoning behind this ?

4 Answers 4

4

Because the value in memory a points to is changed by the assignment a = ["wtv"];.

while in the first example you change a part/property of a, while the object in memory a points to stays the same.

An image to explain it:

enter image description here

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

Comments

2

It's because you're b is just copying a reference to a.

So they have copies of the same reference, but they each have their own copy of that reference.

var a = ["a"];

// b now holds a copy of the reference from a
var b = a;

// when you change a, b is unaffected since it has an independent reference
// a now points to a new location in memory
// a has a new reference, whereas b still has the reference from before
a = ["wtv"];

However, since the two variable do have the same reference, even though they are copies, you can change data within the object or array itself and have it affect both variables.

Take this for example:

// a points to a location in memory
var a = [];

// we give a some value
a["foo"] = 'bar';

// b now has a *copy* of a's location in memory
var b = a;

// since b shares the same location in memory as a, it has the same foo value
console.log(b.foo); // => bar

// we update a's foo value
a["foo"] = 'baz';

// since b still shares the same location in memory as a, 
// it's pointing to the same foo from a, therefore it's also affected
console.log(b.foo); // => baz

@Hidde has a great image that helps visualize what's going on behind the scenes with where the memory is pointing.

Comments

1

With a = ["wtv"]; you assign brand new array to variable a. It has nothing to do with it's former reference.

Comments

1

An array in JavaScript is also an object and objects are always passed/assigned by reference. Thus both variables have a reference to the same object, thus making a change in one will reflect a change in another as both are pointing to the same value.

Whereas in the later case, you are assigning a new value to the var a and this will be stored at different memory location and not on the one on which b is stored, it is similar like doing

var a = 5;
var b = a;
a = a - 1;
alert(b); // alerts 5
alert(a); // alerts 4  

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.