Dmitry Parzhitsky Dmitry Parzhitsky - 4 months ago 10
Javascript Question

The same object is not always the same?

Why

b
is not equal to
null
at the end of the following code?

var a = { property: "value" },
b = a;
console.log(a === b); // true

a = null;
console.log(b); // Object { property: "value" }


I thought that
a
and
b
are two references tied to one object and therefore will both became
null
.

Answer

In the line:

a = 5;

You're pointing 'a' to a new block of memory containing an integer of value 5, overwriting it's previous reference to the object you originally created. Try this instead:

var a = { property: "value" }, 
b = a;
console.log(a === b); // true

a.property = 5;
console.log(b); // Object {property: 5}

This way you're not overwriting a, but rather changing the block of memory the key property points to from a string with value "value", to an integer with value 5.

This preserves a's reference to the block of memory containing the object you originally created, which you also set 'b' to point to in the next line.

Edit: The above was to answer your previous question. If you set a to null, it simply deletes it's reference to the original object. The object won't be garbage collected while anything (b in this case) still has a reference to it. After you create b, the references are independent, but both happen to point to the same block of memory.