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?
Right-associativity of assignment operators In many imperative programming languages, the assignment operator is defined to be right-associative, and assignment is defined to be an expression (which evaluates to a value), not just a statement.
The assignment operator has left-to-right-to-left associativity, which means that the value of the expression to the left of the assignment operator is evaluated first and that the result is assigned to the operand on the right. A string variable can hold digits such as account numbers and zip codes.
If two operators with the same precedence level are adjacent to each other in an expression, the operator's associativity tells the compiler whether to evaluate the operators from left to right or from right to left.
Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: '*' and '/' have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With