var x; x = 0; x = x++; console.log("Value of x: "+x);
Case 1 can be really confused. The result should be “Value of x: 1”. It’s expected that “x++” will increase by 1 and then be assigned to the variable “x” (x = x++;).
However, the correct answer is “Value of x: 0”. This is because this statement does not behave as explained above.
var x; x = 0; x++; console.log("Value of x: "+x);
In this second case the result is the expected one “Value of x: 1”; because the line “x++;”" increase the variable “x” by 1.
In the first case the behavior of the code is equivalent to the following:
var x; x = 0; x = x++; => var temp = x; x = x + 1; x = temp; console.log("Value de x: "+x);
The line “x = x ++;” when assigning the increment itself, the value of “x” is stored in a temporary variable (var temp = x;), which we do not see but that the machine does use internally for after making the increase (x = x + 1;) re-assign that temporary value to the variable “x” so in the result line we have lost an increase that had been made.
Greetings to all