Is There a Difference Between Using i++ and ++i in a JavaScript for Loop?

Differences between i++ and ++i in JavaScript

Although, both ++i (prefix increment) and i++ (postfix increment) mutate the operand (by incrementing its value by one), they return different values. Since in either case the operand value is incremented, you may use either one in the increment part of a for loop. For example:

for (let i = 0; i < 5; ++i) {
    console.log(i); // 0 1 2 3 4
}
for (let i = 0; i < 5; i++) {
    console.log(i); // 0 1 2 3 4
}

However, you have to be mindful of using prefix or postfix increments when you're directly using the return value (such as, in the following examples):

for (let i = 0; i < 5;) {
    console.log(++i); // 1 2 3 4 5
}
for (let i = 0; i < 5;) {
    console.log(i++); // 0 1 2 3 4
}

Also, if you use the prefix/postfix increment directly in another expression, it can lead to different results (and be a source of confusion):

for (let i = 0, j; i < 5; j = i++) {
    console.log(j); // 0 1 2 3
}

for (let i = 0, j; i < 5; j = ++i) {
    console.log(j); // 1 2 3 4
}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.