Reputation: 219
I need to know whether operator Associativity is the same as the order of evaluation of assignment operator and other operators in JavaScript for example
var x;
x = 10;
In the above code I need to know whether the Assignment expression x = 10;
is executed from "right to left" or "left to right" because the operator Associativity of the Assignment operator is "right to left" im a little bit worried about how a normal assignment expression like this x = 10;
is executed. Is it executed from "right to left" or "left to right" where as in the below code you can see the assignment expression is executed from right to left.
var y;
var z;
y = z = 10; // In this snippet you can see that both the variables "y" and "z" hold the value of number 10 this means that the Assignment operator is executed from "right to left";
// Now i must know whether a normal Assignment operator is also executed from "right to left" because Assignment operator is having "right to left" Associativity;
var c;
c = 10; // Not sure whether how and to which side this assignment expression is executed is it executed from "left to right" or "right to left"
Upvotes: 1
Views: 1926
Reputation: 11080
The answer can be found in MDN's page on Operator Precedence (emphasis mine):
Associativity determines how operators of the same precedence are parsed. For example, consider an expression:
a OP b OP c
Left-associativity (left-to-right) means that it is processed as
(a OP b) OP c
, while right-associativity (right-to-left) means it is interpreted asa OP (b OP c)
.
Associativity only comes into play if you have multiple operators of the same precedence. In the case that you have multiple assignment operators, they are evaluated from right to left - but each individual assignment operator is still assigning the right operand to the left name.
In your code snippet:
y = z = 10;
This is equivalent to:
y = (z = 10);
And since an assignment operator evaluates to the value that was assigned (10) you get y = 10;
after z
is assigned.
If you only have one operator, associativity does not apply. In an assignment operator, the right operand is assigned to the left operand, full stop. The order they're evaluated is determined by operator precedence as laid out in the MDN page above.
Upvotes: 2