Assignment associativity

The assignment operator has an associative association from right to left . So,

var x,y;
x=y=1;

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

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

I would expect the above action to look like this:

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

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

+4
source share
1 answer

JavaScript evaluates expressions from left to right. We can show what happens using an additional variable:

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

Due to associativity, the last statement is parsed as:

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

- foo.x (, ), foo, {n: 2}. {n: 2} foo, x foo... , bar:

foo = {"n" : 2}
bar = {"x" : {"n" : 2 }}
+5

All Articles