Search code examples
javascriptgoogle-chromecomparisonobject-equality

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.


Solution

  • 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.