Table of Contents
JavaScript Break , Continue JavaScript Labels in while loop
In JavaScript, the break and continue statements are used to control the flow of execution within loops. Additionally, JavaScript supports labeled statements, which can be used with break and continue to target a specific loop when there are nested loops. Let’s go over each of them with syntax and examples.
break statement
The break statement is used to exit a loop prematurely. When the break statement is encountered inside a loop, the loop is terminated, and the program continues with the next statement after the loop.
*Syntax:*
javascript
while (condition) {
// code block
if (someCondition) {
break; // exit the loop
}
// more code
}
Example
javascript
let i = 0;
while (i < 5) {
console.log(i);
if (i === 3) {
break;
}
i++;
}
// Output: 0 1 2 3
In this example, the loop terminates when i reaches 3 because of the break statement.
continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration.
*Syntax:*
javascript
while (condition) {
// code block
if (someCondition) {
continue; // skip the rest of the loop for this iteration
}
// more code
}
Example
javascript
for (let i = 0; i < 5; i++) {
if (i === 2 || i === 4) {
continue;
}
console.log(i);
}
// Output: 0 1 3
In this example, the continue statement skips the iterations where i is 2 or 4, and the rest of the loop body is not executed during those iterations.
Labels in loops
JavaScript allows you to label loops, which can be useful when dealing with nested loops. You can use labeled statements with break and continue to specify which loop to exit or continue.
*Syntax:*
javascript
outerLoop: while (condition1) {
// code block
while (condition2) {
// code block
if (someCondition) {
break outerLoop; // exit the outer loop
}
// more code
}
// more code
}
Example
javascript
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop;
}
console.log(i, j);
}
}
// Output: 0 0 0 1
In this example, the break outerLoop; statement exits both the outer and inner loops when i is 1 and j is 1.