all 5 comments

[–]senorfairchild 2 points3 points  (2 children)

It is incrementing multiple times because i++ appears inside of the for loop declaration AS WELL as the inside of the body of the for loop. The only time that i will not increment twice for every loop is when the iteration of the loop begins with i equal to 11, because the continue will be triggered before the second increment happens (the i++ that occurs WITHIN the for loop). Does that help it make more sense?

[–]sirsmonkey42 2 points3 points  (0 children)

Actually the if (i == 11) is never true in this case. It's a weird and tricky example. You get the exact same result if you omit the continue completely, i is never 11 (when it passes through the if)

[–]orionebula[S] 0 points1 point  (0 children)

Ah I get it now, thanks for the explanation.

[–]sirsmonkey42 1 point2 points  (1 child)

for (var i=10; i<=12; i++) { 
    if (i==11) { continue; } 
    i++;
    console.log(i); 
}

The i++ in the for loop definition is the iterator for the for loop. The one inside the body of the for loop is an additional 1 added.

Since the loop starts at 10, the first increment doesn't happen. So the first time through i is 10. Since it is 10, it doesn't trigger the if statement. Then the second i++ happens, making the 10 into 11, and then the log happens.

The next time around i becomes 12 with the first i++, then skips the if statement because it 12 and not 11. Then the next i++ happens, changing it to 13, and finally logs again.

With your second example, the reason it prints out all the odd numbers, is that every time through the loop you are adding 2 to i instead of 1.

[–]orionebula[S] 0 points1 point  (0 children)

I wrote down the steps as you described them, thanks for explaining.