I found this problem in a GitHub front-end interview questions collection:
var foo = {n: 1}; var bar = foo; foo.x = foo = {n: 2};Question: What is the value of foo.x?
The answer is undefined.
I've done some research and what I understand this problem is (correct me if I'm wrong):
var foo = {n: 1};declares an objectfoowhich has propertynequal to 1.var bar = foo;declares an objectbarwhich refers to the same object asfoo.foo.x = foo = {n: 2};which I believe is equal tofoo.x = (foo = {n: 2});- And then I got
foo.xequals toundefined. However, the value ofbar.xis the object{n:2}.
If bar and foo refer to same object, why did bar.x get a value while foo.x is undefined? What is really happening in foo.x = foo = {n: 2};?