Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment associativity [duplicate]

Tags:

javascript

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?

like image 297
Unknown developer Avatar asked Jun 11 '16 11:06

Unknown developer


People also ask

What is the associativity of assignment operator?

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.

Does the assignment operator has a left to right associativity?

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.

What happens if two operators have the same level of precedence which one is applied first?

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.

What is meant by associativity explain with an example?

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”.


1 Answers

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 }}
like image 182
melpomene Avatar answered Nov 21 '22 21:11

melpomene