JavaScript Break and Continue

-

The break statement "jumps out" of a loop.

The continue statement "jumps over" one iteration in the loop.

The Break Statement

You have already seen the break statement used 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.

The break statement breaks the loop and continues executing the code after the loop (if any):

var text = "";
var i;

for (i = 0; i < 10; i++) {
if (i === 3) { continue; }   // If i = 3 then skip and continue to the next iteration
text += i;
}

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 3:

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

Live preview - "3" is missed

Exercises - test your knowledge

Exercise 1

Make the loop stop when i is 5.

for (i = 0; i < 10; i++) {
console.log(i);
}

for (i = 0; i < 10; i++) {
console.log(i);
if (i == 5) {
break;
}
}

Exercise 2

Make the loop jump to the next iteration when i is 5.

for (i = 0; i < 10; i++) {
console.log(i);
}

for (i = 0; i < 10; i++) {
console.log(i);
if (i == 5) {
continue;
}
}

Rate this lesson 