Hi,
This is my first post and I would like to raise and resolve a javascript code behavior issue according to the following two cases:
CASE 1
According to the following javascript code, what is the result?
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.
CASE 2
According to the following javascript code, what is the result?
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.
The above demonstrates that “x = x + 1;” is different from “x = x ++;” since they don’t behave the same. In the first case “x = x + 1;” the increment is made then assigned to the variable “x”. In the second case “x = x ++;” is also done but subsequently we lose it by assigning the temporary variable to the variable “x” that system performs internally. In addition, this behavior doesn’t happen only in javascript, the same happens in every programming language.
Greetings to all