Hossein Shourabi
MrCatDev's Blog

MrCatDev's Blog

When should I use prefix increment operator (++i)?

When should I use prefix increment operator (++i)?

Hossein Shourabi's photo
Hossein Shourabi
·Feb 1, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

When should I use prefix increment operator (++i)?

Sometimes I need to increment the original value first, then return it value. So this operator is exactly what I need.

How it (++i) works?

Let's look at this example:

let i = 2;
let counter = ++i * 2;

The perfix increment operator (++i) equivalent to:

i = i + 1;   
/* 
* i=> 3
*/
let counter = i * 2;
/* 
*  counter => 3 * 2 = 6
*/

As you can see the i incremented, then multiplication by 2

More Example

In the following code, before starting the while loop, the i operand is incremented one step, then checked in the while condition.

let i = 0;
while (++i < 3) console.log(i);

above example equivalent to:

let i = 0;
i = i + 1;
while ( i < 3) {
  i = i + 1;
  console.log(i)
};

You can find a practical example in this article that I wrote it with JavaScript.

Reference

1- Mozila

2- JavaScript Info

Thanks for reading.

 
Share this