Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 24, 2021 02:37 pm GMT

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 incrementlet i = 3;const j = i++;console.log({ i, j }); // { i: 4, j: 3 }
Enter fullscreen mode Exit fullscreen mode
// prefix incrementlet 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.


Original Link: https://dev.to/kais_blog/the-difference-between-i-and-i-postfix-vs-prefix-4ape

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To