JavaScript The break and continue Statements


The break statement is used to jump out of a loop.

continue is used to skip one iteration in a loop.


The break Statement

We have already seen the break statement in an earlier chapter of this tutorial. It was used to jump out of a switch() statement.

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

After the break statement jumps out of the loop, it continues to execute the code after the loop (if any):

Example

for (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + "<br>"; }

Try it Yourself »

Since this if statement has only one line of code, the curly braces can be omitted:

for (i=0;i<10;i++) { if (i==3) break; x=x + "The number is " + i + "<br>"; }


The continue Statement

The continue statementIt breaks the current iteration in the loop, and then continues with the next iteration in the loop. In the following example, when the value is 3, it directly skips it:

For Loop Example

for (i=0;i<=10;i++) { if (i==3) continue; x=x + "The number is " + i + "<br>"; }

Try it Yourself »

While Loop Example

while (i < 10){ if (i == 3){ i++; //Adding i++ will not cause an infinite loop continue; } x= x + "The number is" + i + "<br>"; i++; }

Try it Yourself »


JavaScript Labels

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

To label a JavaScript statement, precede it with a label and a colon:

label: statements

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

Syntax:

break labelname; continue labelname;

The continue statement (with or without a label reference) can only be used inside loops.

The break statement (without a label reference) can only be used inside loops or switch.

With a label reference, the break statement can be used to jump out of any JavaScript code block:

Example

cars=["BMW","Volvo","Saab","Ford"]; list: { document.write(cars[0] + "<br>"); document.write(cars[1] + "<br>"); document.write(cars[2] + "<br>"); break list; document.write(cars[3] + "<br>"); document.write(cars[4] + "<br>"); document.write(cars[5] + "<br>"); }

Try it Yourself »
Other Extensions