Why is the result of the program undefined?

var foo = {}; foo.c = foo = {}; console.log(foo.c); 

why is the result undefined? I thought it should be "[object Object]"

+6
source share
2 answers

In assignments, strange things happen here:

 foo.c = (foo = {}) 

The reference to foo.c first resolved and points to the old foo object before the internal expression is evaluated, where foo will be re-assigned with the literal {} emtpy object. So your code is equivalent

 var foo1 = {}; var foo2 = {}; foo1.c = foo2; console.log(foo2.c) // obviously undefined now 

You can also try

 var foo = {}, old = foo; foo.c = foo = {}; console.log(old, foo, old.c===foo); // {c:{}}, {}, true 
+11
source

The JavaScript engine breaks down this purpose:

 a = b = c = 1; 

Properly:

 a = 1; b = 1; c = 1; 

And not like:

 c = 1; b = c; a = b; 

There is a small but important difference - basically it includes getters, please check Multiple variable assignments on one line for more details - and basically why your code does not work as expected expectations are based on false assumptions.

0
source

All Articles