Summary: in this tutorial, you will learn how to use the JavaScript break statement to control the execution of code in a loop.
Before discussing the break statement, let’s talk about the label statement first.
The label statement
In JavaScript, you can label a statement for later use. The following illustrates the syntax of the label statement:
label: statement;
Code language: HTTP (http)The label can be any valid identifier.
The following example labels the loop using the outer label.
outer: for (let i = 0; i < 5; i++) {
console.log(i);
}Code language: JavaScript (javascript)You can reference the label by using the break or continue statement. Typically, you use the label with nested loop such as for, do-while, and while loop.
JavaScript break statement
The break statement gives you fine-grained control over the execution of the code in a loop. The break statement terminates the loop immediately and passes control over the next statement after the loop. Here’s an example:
for (var i = 1; i < 10; i++) {
if (i % 3 == 0) {
break;
}
}
console.log(i); // 3Code language: JavaScript (javascript)In this example, the for loop increments the variable i from 1 to 10. In the body of the loop, the if statement checks if i is evenly divisible by 3. If so, the break statement is executed and the loop is terminated.
The control is passed to the next statement outside the loop that outputs the variable i to the console window.
Besides controlling the loop, you also use the break statement to terminate a case branch in the switch block. See how to use the break statement in the switch block.
Using break statement to exit nested loop
As mentioned earlier, you use the break statement to terminate a label statement and transfer control to the next statement following the terminated statement. The syntax is as follows:
break label;Code language: JavaScript (javascript)The break statement is typically used to exit the nested loop. See the following example.
let iterations = 0;
top: for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
iterations++;
if (i === 2 && j === 2) {
break top;
}
}
}
console.log(iterations); // 13Code language: JavaScript (javascript)In this example:
- First, the variable
iterationsis set to zero. - Second, both loops increase the variable
iandjfrom1to5. In the inner loop, we increase theiterationvariable and use anifstatement to check bothiandjequal 2. If so, thebreakstatement terminates both loops and passes the control over the next statement following the loop.
In this tutorial, you have learned how to use the JavaScript break statement to control the code execution of code in a loop and how to exit a nested loop.