Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
Yes, there is a difference between ++i
and i++
in a for
loop, though in unusual use cases; when a loop variable with increment/decrement operator is used in the for block or within the loop test expression, or with one of the loop variables. No it is not simply a syntax thing.
As i
in a code means evaluate the expression i
and the operator does not mean an evaluation but just an operation;
++i
means increment value of i
by 1 and later evaluate i
,i++
means evaluate i
and later increment value of i
by 1.So, what are obtained from each two expressions differ because what is evaluated differs in each. All same for --i
and i--
For example;
let i = 0
i++ // evaluates to value of i, means evaluates to 0, later increments i by 1, i is now 1
0
i
1
++i // increments i by 1, i is now 2, later evaluates to value of i, means evaluates to 2
2
i
2
In unusual use cases, however next example sounds useful or not does not matter, it shows a difference
for(i=0, j=i; i<10; j=++i){
console.log(j, i)
}
for(i=0, j=i; i<10; j=i++){
console.log(j, i)
}