WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Break and Continue


break statement is used to break out of a loop.

continue skips an iteration in a loop.


The Break Statement

We have seen break statements in previous chapters of this tutorial. It is used to jump out of the switch () statement.

The break statement can be used to break out of a loop.

After the break statement breaks out of the loop, it will continue to execute the code after the loop (if any):

Example

for (I = 0; I < 10; i++) {
    if (I === 3) { break; }
    text += "The number is " + I + "<br>";
}
Try it yourself »

The Continue Statement

The continue statement interrupts the iteration in the loop, and if the specified condition occurs, then continues to the next iteration in the loop. This example skips the value 3:

Example

for (I = 0; I < 10; i++) {
    if (I === 3) { proceed; }
    text += "The number is " + I + "<br>";
}
Try it yourself »

JavaScript Labels

As you saw in the chapter on switch statements, you can mark JavaScript statements.

To mark a JavaScript statement, precede the statement with a colon:

label:
statements

The break and continue statements are just statements that can jump out of a code block.

Syntax:

break labelname;

continue labelname;

continue statements (with or without label references) can only be used in loops.

Break statement (without label reference) can only be used in loops or switches.

Break references can be used to break out of any JavaScript code block:

Example

var car = ["BMW", "Volvo", "Saab", "Ford"];
list: {
    text += cars[0] + "<br>";
    text += cars[1] + "<br>";
    text += cars[2] + "<br>";
    text += cars[3] + "<br>";
    break list;
    text += cars[4] + "<br>";
    text += cars[5] + "<br>";
}
Try it Yourself »