DEV Community

Cover image for The Difference Between i++ and ++i (Postfix vs. Prefix)
Kai
Kai

Posted on • Originally published at kais.blog

The Difference Between i++ and ++i (Postfix vs. Prefix)

This post was originally published at kais.blog.

Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!


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++;
Enter fullscreen mode Exit fullscreen mode

In this case it's almost equivalent to:

i = i + 1;
Enter fullscreen mode Exit fullscreen mode

But, what do you think? Is there a difference between

let i = 3;
const j = i++;
Enter fullscreen mode Exit fullscreen mode

and

let i = 3;
const j = ++i;
Enter fullscreen mode Exit fullscreen mode

...

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 }
Enter fullscreen mode Exit fullscreen mode
// prefix increment

let i = 3;
const j = ++i;

console.log({ i, j }); // { i: 4, j: 4 }
Enter fullscreen mode Exit fullscreen mode

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!


Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!

This post was originally published at kais.blog.

Top comments (2)

Collapse
 
tadjerounimohamedadel profile image
Adel Mohamed Tadjerouni

Nice

Collapse
 
phuocng profile image
Phuoc Nguyen

Thanks for the post. I also share more differences on thisthat.dev. Hopefully, it's useful.