I have an example:
let x = 4
console.log(x++ + ++x + x--)
it's returns 16
but I don't understand how. If we will look in MDN there is an operators precedence table. So there is a precedence like this:
- Postfix increment
- Postfix decrement
- Prefix increment
- Addition
With this logic it should return 14
x++
= 4 - (5) -> remembers for next callx--
= 5 - (4) -> remembers for next call++x
= 5+
4 + 5 + 5 = 14
Can some one explain, how operators parser algorithm works with unary and binary operators?
The order is completely consistent. You are evaluating left-to-right and apply the precedence. I'll break it down in steps:
1. Post-increment x++
//x = 4
x++ + ++x + x--
^^^
|
--> expression = 4
--> x = 5
First off we evaluate x++
. Postfix increment has higher precedence than the addition, so we have to solve it first. This expression produces 4
(value of x
at the time) however, the value of x
is also incremented for future reads.
2. Pre-increment ++x
//x = 5
4 + ++x + x--
^^^
|
--> x = 6
--> expression = 5
Next ++x
is evaluated, as prefix increment also has higher precedence than the addition, so we have to resolve it before the expression a + b
. We aren't concerned with x--
yet, since we've not gotten to it.
Thus, the prefix increment will increase the value of x
from 5
to 6
and then return that new value.
3. Addition (x++) + (++x)
//x = 6
4 + 6 + x--
^^^^^
|
--> expression = 10
We've resolved the higher priority expressions, so it's time for the addition. Which is simple 4 + 6 = 10
.
4. Post-decrement x--
//x = 6
10 + x--
^^^
|
--> expression = 6
--> x = 5
We're reached another a + b
construct but the postfix decrement x--
is higher priority, so we solve that first. Current value of x
is 6
and we return that, then do the decrement of x
to 5
.
5. Addition ((x++) + (++x)) + (x--)
//x = 5
10 + 6
^^^^^^
|
--> expression = 16
Finally, another simple addition after everything with higher precedence is resolved: 10 + 6 = 16