-4

I'm having trouble understanding how work Postfix and Prefix Increment in expression like this:

var x = 1;
x = ++x + x++ * x

Why browser console return 8 ?

5 Answers5

6

It is evaluated left to right:

++x           : x is now 2
++x +         : 2 + 
++x + x       : 2 + 2
++x + x++     : 2 + 2 and x is now 3
++x + x++ *   : 2 + 2 *
++x + x++ * x : 2 + 2 * 3
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
2

var x = 1; x = ++x + x++ * x

As per

++x => 2 (After pre-fix's updated value)
x++ => 2 (Post-fix will update in second sequence not now)
x   => 3 (After post-fix's updated value)

so

x = 2 + 2 * 3 

As per multiplication in priority it would

x = 2 + 6

hence

x = 8 
Anupam Maurya
  • 1,927
  • 22
  • 26
1

You can learn more at this website: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment Here are the reasons:

  1. x = 1; X is 1.
  2. x = ++x; now x is incremented by 1. (X is 2)
  3. x = ++x + x++ * x

Since multiplication is always calculated first, we will multiply x++ by x. Remember, x has value of 2.

This is what looks like in math expression:

x = 1; 
x = 1+1+2+1*3

We will multiply x++ by x. Remember, x is 2. So it will look like this:

x = 1+1 +(2+1{2})

Now we will calculate the numbers inside the pearenthesis.

2+1*2 = 6

After that, we can add 2 to 6 to get 8.

2+6 = 8

This is why.

0
x = ++x + (x++ * x)

See it as a math operation, form left to right.

++x = x is now 2
x++ = x is now 3 but the showed value remains 2
x = is 3

x = 2 + (2 * 3)
x = 8
0

According to operator precedence sequence will be executed and returns values by following steps:

++x => 2 // returns current value after increment
x++ => 2 // returns old value, here old value is 2 because already increment before
x++ * x => 2 * 3 => 6  // x returns stored current value after 2 times increment
++x + 6 => 2 + 6 => 8 // Output is 8

NOTE ++x and x++ both increases variable by 1 and store value to the variable(x). But here is simple difference ++x (prefix increment operator) returns current value and x++ (postfix increment operator) returns old value.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nurmdrafi
  • 419
  • 4
  • 11