Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inconsistency in application of the increment operator when used in expressions

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

JavaScript is strictly evaluated left-to-right. That means the left operand of + is evaluated before its right operand.

  • If the left-hand side expression changes x, this change will already be visible when the right-hand side is evaluated
  • If the right-hand side expression changes x, this change happens only after the left-hand side was evaluated

So for your examples, we have the step-by-step evaluations

y = x + x++ // x: 1
y = 1 + x++ // x: 1
y = 1 + 1 // x: 2
y = 2 // x: 2

y = x++ + x // x: 1
y = 1 + x // x: 2
y = 1 + 2 // x: 2
y = 3 // x: 2

y = x + x++ + x // x: 1
y = 1 + x++ + x // x: 1
y = 1 + 1 + x // x: 2
y = 2 + x // x: 2
y = 2 + 2 // x: 2
y = 4 // x: 2

y = x + ++x + x // x: 1
y = 1 + ++x + x // x: 1
y = 1 + 2 + x // x: 2
y = 3 + x // x: 2
y = 3 + 2 // x: 2
y = 5 // x: 2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading