0

clarify code output

WHY is the output 9? var x = 0; for (; x <= 8; x++) { x += x - x++; } console.log(x); There is something missing me in this line "x += x - x++;" Could someone unwrap this so that I can understand what is happening, please? Because I thought it would be equivalent to this: "x = x + x - x; x++; " but it's not true!!

3rd Apr 2020, 6:55 AM
Radu Harangus
Radu Harangus - avatar
3 Réponses
+ 4
x += expression is equivalent to: x = x + (expression) //notice the parenthesis. The same is true for other shorthand assignments. x = x + (x - x++); x - x++ is always 0 so you are just saying x = x + 0(doing nothing) when x = 9 the for loop condition is false and we jump to the console.log part.
3rd Apr 2020, 7:04 AM
Kevin ★
+ 5
x++ returns x first and increments the value of x later. Expressions are evaluated from left to right and when we increment x in this code we are not getting its value anymore we are simply evaluating a math expression and assigning its result to x. Let's say x = 5 and let's make substitutions: x = 5 + (5 - 5); //now x = 6 because we increment it but we don't need that 6; x = 5 + 0 //x is still 6; x = 5 //x=5 because we are not using the incremented value of x but the returned value of the math expression.
3rd Apr 2020, 4:21 PM
Kevin ★
+ 1
@Kevin Star thank you, but one more thing please: why x - x++ == 0 ? and not 1 ?
3rd Apr 2020, 7:44 AM
Radu Harangus
Radu Harangus - avatar