Because the property access foo.x
on the left is evaluated before the right-hand side.
Let's make it more clear what your code actually does, by giving new names to the temporary expressions being evaluated:
var foo0 = {n: 1};
var foo1 = {n: 2};
foo0.x = foo1;
foo0 = foo1;
console.log(foo0.x);
Hence foo0.x
is foo1.x
is undefined
.
In your original code, you can see that bar.x
is {n: 2}
, confirming this explanation.