Reputation: 29
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 ?
Upvotes: -3
Views: 5713
Reputation: 1045
Prefix (++variable) When the ++ operator is used before the variable, it increments the variable’s value before the value is used in the expression
let a = 5;
let b = ++a; // a is incremented to 6, then b is assigned the value of 6
console.log(a); // 6
console.log(b); // 6
Postfix (variable++) When the ++ operator is used after the variable, it increments the variable’s value after the value is used in the expression.
let a = 5;
let b = a++; // b is assigned the value of 5, then a is incremented to 6
console.log(a); // 6
console.log(b); // 5
Upvotes: -1
Reputation: 529
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.
Upvotes: 0
Reputation:
You can learn more at this website: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment Here are the reasons:
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.
Upvotes: 1
Reputation: 1
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
Upvotes: 0
Reputation: 2201
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
Upvotes: 2
Reputation: 31682
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
Upvotes: 6