When JavaScript encounters a continue statement in a loop it stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration. The example below displays only even numbers.
for (var i = 1; i <= 10; i++)
{
if ((i % 2) != 0)
{
continue;
}alert(i); // => 2, 4, 6, 8, 10
}
The continue statement can also be used in other loops. However, in a for-loop it behaves differently from when used in a while loop. In the example above, the for-loop first evaluates the i++ expression and then tests the i <= 50 condition. Now, consider the while loop:
var number = 0;
while (number <= 10)
{
number++;
if ((number % 2) != 0)
{
continue;
}alert(number); // => 2, 4, 6, 8, 10
}
When the continue statement is executed, the control is returned directly to the while (number <= 50) test condition and the number++ expression is not evaluated, thus causing an infinite loop. The lesson here is that you cannot simply replace a for loop with a while loop; you have to be careful especially when a continue statement is involved.