0
i = 0;
for( ;i<3; ){
  alert(i++);
}

The above code should output a '1' after the first iteration as 'i' has been initialized as 0. Instead, the first alert brings up a '0'. How is this logically correct as the first output should've been the incremented value itself?alert(i++);
This is syntactically equal to the code

for (let i=0; i<3; i++)
{
    alert(i);
}
  • 1
    The final expression runs only at the end of the loop. While understanding pre vs post increment explains it, a better approach (IMO) is to not use them when their result is used as an expression, because it's confusing. Increment as a separate statement, after the `alert`, and it'll be a lot clearer what's going on. – CertainPerformance Jul 08 '22 at 03:59
  • A post-increment returns the *old value* of `i`, and increases `i` to its new value; So, for the first iteration, `alert(i++)` is basically `alert(0); i=1` – qrsngky Jul 08 '22 at 04:07
  • @CertainPerformance so does it mean that the alert first returns the original value of i and then the incremented value? – GimmeGinNtonic Jul 08 '22 at 04:12
  • In your first snippet, post-increment increments the value and returns the value before the increment. That returned (unaltered) value is then alerted. Then that iteration ends, and the next iteration begins, and the process repeats. – CertainPerformance Jul 08 '22 at 04:19
  • @GimmeGinNtonic `alert` does not return a value of i. You can try `console.log(alert(0))` which tells you that the result of `alert(0)` is `undefined`. I would say that `alert` _uses_ the value you supply, and then returns undefined. In this case, `alert` uses an older value of `i`. – qrsngky Jul 08 '22 at 04:21
  • @CertainPerformance then according to your explanation, The returned value in the first iteration was 0 and then that got alerted and the initial value of `i` in the second iteration was 1 which was the incremented result of the first iteration and will get alerted as part of this iteration. i hope i got it right this time – GimmeGinNtonic Jul 08 '22 at 04:42
  • Yes, that's how it's working – CertainPerformance Jul 08 '22 at 04:42

0 Answers0