Reputation: 483
Please consider this snippet of code:
var i = 1;
i = i-- + ++i;
My understanding of the order in which the operators & operands are processed is as follows:
If my understanding is correct, i should end up having a value of 3. However, I printed out the result using some online javascript interpreter, and the end value of i is 2.
Where did I get wrong?
Upvotes: 0
Views: 97
Reputation: 377
Understanding the logic with precedence values:
var i = 1;
i = i-- + ++i;
prefix increment(++i) precedence = 17
postfix decrement(i--) precedence = 16
addition(+) precedence = 14
i = 1 + 1
i = 2
More precedence related info can be found in, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Upvotes: 0
Reputation: 869
var i = 1;
i = i-- + ++i;
this is how the compiler will go about working through this code
Upvotes: 2
Reputation: 40804
JavaScript always evaluates subexpressions in a left-to-right order, and then applies the operator:
// parentheses added for clarity
i = (i--) + (++i); // i = 1
i = 1 + (++i); // i = 0 after i--
i = 1 + 1 ; // i = 1 after ++i
i = 2 ;
Upvotes: 2