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

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
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.