Can anyone tell how the output became undefined
?
var foo = {n: 2};
foo.x = foo = {n: 2};
console.log(foo.x); // undefined
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 });
var foo = { n: 2 };
foo.x = foo = { n: 2 };
console.log(foo.x);