++i vs. i++ in Javascript

Jamie Skinner
1 min readMay 2, 2015

There is a small but important difference between ++i and i++ that can give quite a headache if you aren’t careful. Try this:

var i = 5;
i++;
console.log(i); //=> logs 6
++i;
console.log(i); //=> logs 7

As expected, both versions increment i. The difference comes in when the expression actually resolves. If we make one small change we get drastically different results.

var i = 5;
console.log(i++); //=> logs 5
console.log(i); //=> logs 6

This means that the value i doesn’t actually resolve until after the console.log. This can be tricky especially if you are making comparisons

var i = 5;
console.log(++i === i++) //=> false

On the other hand ++i resolves before any operations are called on it.

var i = 5;
console.log(++i)//=> 6

So what is the solution? Don’t use either! Use i += 1. This behavior is predictable across the board, and you won’t likely confuse it with anything else!

--

--