Search code examples
javascriptassignment-operator

Double-assignment of an object property results in undefined property


Can anyone tell how the output became undefined?

var foo = {n: 2};
foo.x = foo = {n: 2};
console.log(foo.x); // undefined

Solution

  • foo.x = foo = { n: 2 };
    

    The foo.x refers to the property x of the object referred to by foo. However, foo = { n: 2 } assigns a completely new object to foo. x is indeed assigned to an object, but that object is immediately replaced by another object. The object with the x property isn’t referenced by anything anymore.

    You can read that line as

    foo.x = (foo = { n: 2 });
    

    Graphical explanation

    var foo = { n: 2 };
    

    First object is assigned to foo

    foo.x = foo = { n: 2 };
    

    foo is reassigned to a second object, but foo.x still points to the first object.

    console.log(foo.x);
    

    Trying to access foo.x actually accesses the x property of the second object.