Post-increment Operator Does Not Increment Variable Until After Evaluation
I am searching for a reason for why increment operator doesn't increment the numeric value in the place where I set the innerHTML value, like below:
Solution 1:
It does increase the variable, however it writes to the innerHTML then increments the value, You could use ++a
which will increase the value before it writes to the innerHTML.
var a = 14var b = 14console.log('before a', a)
document.getElementById("test1").innerHTML = a++
console.log('after a', a)
console.log('before b', b)
document.getElementById("test2").innerHTML = ++b
console.log('after b', b)
<divid="test1"></div><divid="test2"></div>
Solution 2:
Instead of using a++
you can do ++a
to get the increment before the variable value assignation:
var a = 14;
document.getElementById("php").innerHTML = ++a;
<divid="php"></div>
Solution 3:
Because you use the postfix increment operatorvariable++
, that means you get the value first and then the variable is incremented.
When you use prefix increment operator ++variable
, the variable gets incremented first and then the value is returned.
var a = 42;
console.log(a++); // shows 42, value is 43console.log(a); // 43console.log(++a); // 44console.log(a); // 44
Post a Comment for "Post-increment Operator Does Not Increment Variable Until After Evaluation"