Search code examples
javascriptoperatorsoperator-precedencepost-increment

Assignment along with Post increment


I am a bit confused with the output. Tried in Javascript

var x = 1;
x = x++;
console.log(x); //Its output is 1

I was thinking it to be 2. because I am doing the print after the post-increment. Any views on it?


Solution

  • The order in which x = x++ is executed is as follows:

    • Old value of x is calculated (oldValue = 1)
    • New value for x is calculated by adding 1 to old value (newValue = 2)
    • New value is assigned to x. At this point x becomes 2!
    • Old value is returned (return value is 1). This concludes the evaluation of x++
    • The old value is assigned to x. At this point x becomes 1

    The above rules are described here. The rules indicate that x is incremented before assignment, not after.