javascriptfor-loopincrement

Why does Javascript's for() loop increment the counter beyond the break condition after the loop?


Can anyone tell me why for loop increments even on failed iteration?

for (var n = 0; n <3; n++) {
     alert(n);                  // displays 0 , 1 , 2 
}
alert(n); // gives 3 

But shouldn't it be like

if(condition):
    //desired stuff
    increment;
else:
    exit;

I seldom use iteration variable mostly I just throw them away upon loop completion but in this case found it to be the cause of a bug


Solution

  • Conceptually n++ is called just after the final statement of the loop body, and the stopping condition is evaluated just before the first statement of the loop body.

    So your code is equivalent to

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

    Viewed this way, the reason why n is 3 once the loop exists ought to be obvious.

    Note that in javascript, n leaks out of the for loop.