5

The assignment operator has right-to-left associativity. So

var x,y;
x=y=1;

works as expected and x equals 1. Consider now the code:

var foo={};
foo.x = foo = {n: 2};

I would expect the above to work like the following:

var foo = {n: 2}; 
foo.x=foo;

However, in the first case foo.x is undefined while in the second case foo.x points to foo (circular reference). Any explanation?

Unknown developer
  • 5,414
  • 13
  • 52
  • 100

1 Answers1

7

JavaScript evaluates expressions from left to right. We can show what's going on by using an additional variable:

var foo = {};
var bar = foo;  // keep a reference to the object originally stored in foo
foo.x = foo = {n: 2};

Because of associativity, the last statement is parsed as:

foo.x = (foo = {n: 2});

But because of evaluation order, foo.x runs first (determining where to store the value), then foo, then {n: 2}. So we store {n: 2} in the variable foo, then assign the same value to the property x of the old contents of foo ... which we can see by looking at bar:

foo = {"n" : 2}
bar = {"x" : {"n" : 2 }}
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Any reference to back the claim that assignment expressions are evaluated from left to right? – haim770 Jun 13 '16 at 17:52
  • @haim770 I found "*ECMAScript specifies left to right evaluation of expressions*" in http://www.ecma-international.org/ecma-262/6.0/. – melpomene Jun 13 '16 at 18:25
  • If interpreter store `{n: 2}` in variable `foo`, and *then* assign the same value to the property `x`, why variable `foo` contains the old content? I don't understand. – Yuri Beliakov Apr 15 '19 at 10:18
  • @YuriBeliakov What do you mean by "old content"? – melpomene Apr 15 '19 at 19:38