Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 962
Vinay Avatar asked May 30 '26 12:05

Vinay


2 Answers

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.

like image 185
Bathsheba Avatar answered Jun 02 '26 02:06

Bathsheba


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

Working of for loop is as follows -

  1. First it initialize the n to 0;

  2. Then it checks the condition whether it is true or not in this case condition is n<3.

    1. Finally it increments the n and again check the condition and if it is true,It again goes in for block. And if the condition is false, It exit the for loop.

In your code when n=3 condition get false. So final value of n is 3.

like image 36
Sushil Kumar Avatar answered Jun 02 '26 02:06

Sushil Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!