The Difference Between i++ and ++i (Postfix vs. Prefix)
JavaScript (and many other languages) support the postfix and the prefix increment operator (++
). You have probably seen and used it before.
Often it's used like this:
i++;
In this case it's almost equivalent to:
i = i + 1;
But, what do you think? Is there a difference between
let i = 3;
const j = i++;
and
let i = 3;
const j = ++i;
...
Well, yes. The first example uses the postfix increment operator (i++
). The second example uses the prefix increment operator (++i
). At first, it seems like there's no difference. However, it's important to understand what is going on here:
The postfix increment operator increments the value and returns the value before the increment.
The prefix increment operator increments the value and returns the value after the increment.
Let's take a look at our two examples again:
// postfix increment
let i = 3;
const j = i++;
console.log({ i, j }); // { i: 4, j: 3 }
// prefix increment
let i = 3;
const j = ++i;
console.log({ i, j }); // { i: 4, j: 4 }
Spotted the difference? The value of j
differs. Therefore, it is important to know this small difference between postfix and prefix.
By the way, the same applies to the postfix decrement and prefix decrement operator (--
). The only difference is, that instead of incrementing we are decrementing the value.
That's all there is to say. I hope I made the difference a bit clearer. See you soon!