Search code examples
javascriptincrementdecrement

Explain, please, these ++ and -- operations


Why this code outputs 3, not 2?

var i = 1; 
i = ++i + --i; 
console.log(i);

I expected:

++i // i == 2
--i // i == 1
i = 1 + 1 // i == 2

Where I made mistake?


Solution

  • The changes occur in this order:

    1. Increment i (to 2)
    2. Take i for the left hand side of the addition (2)
    3. Decrement i (to 1)
    4. Take i for the right hand side of the addition (1)
    5. Perform the addition and assign to i (3)

    … and seeing you attempt to do this gives me some insight in to why JSLint doesn't like ++ and --.