JavaScript Loop Control
JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.
JavaScript break Statement
The break statement is used to exit a loop early, breaking out of the enclosing curly braces.
The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace:
Example:
while (count < 10) {
if (count == 5) {
break;
}
document.write ("Current Count : " + count );
count++;
}
Run Example
JavaScript continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5:
Example:
while (count < 10) {
count++;
if (count == 5) {
continue;
}
document.write ("Current Count : " + count );
}
Run Example