user3723041 user3723041 - 1 year ago 88
Javascript Question

Double-assignment of an object property results in undefined property

Can anyone tell how the output became


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

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

The foo.x refers to the property x to the object refered 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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download