Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reference = null not affect the referenced object?

I know this works, but I don't know why or the reasoning behind why it was made to work this way:

var foo = [5, 10];
var bar = foo;
console.log(foo); //[5, 10]
console.log(bar); //[5, 10]
bar[0] = 1; 
console.log(foo); //[1, 10]
bar = null;
console.log(foo); //[1, 10]

I would have expected not just bar to become null, but foo as well. I'd love some help understanding this.

like image 471
Bloodyaugust Avatar asked Apr 18 '26 00:04

Bloodyaugust


1 Answers

When you do bar = null; that just assigns something to the value of the bar variable. It does not affect what used to be assigned to bar. That object continues to live on and if there are other references to it, it stays alive with its value untouched.

When you do this:

var foo = [5, 10];
var bar = foo;

You have three entities. You have an array [5,10] and two variables each with a reference to that array. If you change the array, then since both variables point to the same array, you will see that change no matter which variable you reference the array through.

But, if you set bar = null, that just affects the bar variable which then no longer has a reference to the array. It doesn't affect the array at all which is still pointed to by foo.

In fact, if you did this:

var foo = [5, 10];
var bar = foo;
bar = [20,30];

You'd have the same sort of result. After the second line of code both bar and foo pointed to the same array, but after the third line, bar now points to a new array and only foo points to the original array. The key is realizing that there's a difference between using bar to modify the object it points to as in bar[0] = 1 versus reassigning the whole value of bar as in bar = [20,30]. In the first case, the underlying object that both foo and bar point to is changed. In the second case, the underlying object that bar originally pointed to is not touched. Instead, bar is changed to point a new object and the prior object is not touched.

like image 95
jfriend00 Avatar answered Apr 20 '26 12:04

jfriend00