In JavaScript we have postfix (x++) and prefix (++x)increment like many other C derivative syntax. I know that both prefix and postfix increment has a higher precedence than addition.
So if we do the following, y gets the value 2, as x (as 1) gets added to x (as 1) and then x gets incremented to 2.
x = 1
y = x + x++
However, if then I do the following y gets the value 3. Why is it not 2 like the other example? Or conversely, why is the other example giving 2 if the rules of precedence are being obeyed?
x = 1
y = x++ + x
Another example of where you can see this is in the following examples:
In this example y has the value 4. But really what is going on here semantically? I guess because its assign and then increment, the x first represents 1 so we have 1 + 1, then its incremented, and next we add it to x (which is now 2) making 4.
x = 1
y = x + x++ + x
But, then we have an inconsistency. Take a look at the following, what is semantically going on here? The result I got in y was 5, and not 6 like I expected.
x = 1
y = x + ++x + x
Here is my take what I think should be happening First x++ is evaluated incrementing x to 2, then this is added to the first x (which is now 2) making 4, this value should then be added to the second x making 6. But, that is not what happens Y gets 5 when I try this in the REPL.
Why is it 5?
2
Answers
JavaScript is strictly evaluated left-to-right. That means the left operand of
+
is evaluated before its right operand.x
, this change will already be visible when the right-hand side is evaluatedx
, this change happens only after the left-hand side was evaluatedSo for your examples, we have the step-by-step evaluations
The postfix
++
increment will return the original value before incrementing immediately after. As JavaScript is evaluated left to right, any value after the increment would have been incremented.Below is what your
x++ + x
statement evaluates to:1 + 2
x++
returns 1, then increments by one causing the followingx
to be2
.