Strange behaviour of for loops

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 

In terms of pseudo-code it is like

  • For loop Variations in javascript
  • why -1 is falsy ? - for (
  • angularjs for loop for birthday field
  • Debugging loop and function - javascript
  • Javascript/jquery for loop array
  • Calling an asynchronous function within a for loop in JavaScript
  • if(condition):
        //desired stuff
        increment;
    else:
        increment;
        exit;
    

    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

  • For loop on an object is getting out of control
  • For Loop optimization in Javascript
  • Javascript for loop with iterator In the middle and decrement operator to the left of i?
  • Having trouble with a for loop not iterating enough
  • How to loop through Array of Objects to find ID then return a sibling key
  • Create multiple variables inside for loop
  • 4 Solutions collect form web for “Strange behaviour of for loops”

    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.

    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.

    Just executed the code at chrome console:

    enter image description here

    It works as expected.

    As you have commented that n will be alert with 3, it is wrong, because when n will be 2, condition will be checked i.e. 2<2 will be wrong, then it will be jump from the loop and will alert 2 not 3.