break & continue: Flow Control & Labeled StatementsThe break statement immediately terminates the current loop or switch block. The continue statement skips the remainder of the current iteration and jumps directly to the next loop evaluation. Labels allow control statements to target specific outer nested loops.
break vs continue Execution Pathflowchart TD
Loop["Loop Iteration"] --> CheckItem{"Inspect Item"}
CheckItem -- "continue hit" --> Skip["Skip remaining body -> Next Iteration"]
CheckItem -- "break hit" --> Exit["Terminate Loop Entirely"]
CheckItem -- "Normal" --> Exec["Execute remaining body"]
| Keyword | Action | Target |
|---|---|---|
break |
Aborts and exits loop completely. | Innermost enclosing loop or switch (or labeled block). |
continue |
Skips current iteration body. | Innermost enclosing loop (jumps to increment step). |
label: |
Names a statement block or loop. | Target for break labelName or continue labelName. |
// Demonstrating break, continue, and labeled loops
// 1. continue: Skipping odd numbers
console.log("--- Filter Even Numbers with continue ---");
for (let i = 1; i <= 5; i++) {
if (i % 2 !== 0) {
continue; // Skip rest of loop body for odd numbers
}
console.log(`Even Number: ${i}`);
}
// 2. break: Short-circuit search
console.log("
--- Early Exit Search with break ---");
const items = ["Apple", "TargetItem", "Banana", "Cherry"];
for (const item of items) {
if (item === "TargetItem") {
console.log(`Found target item '${item}'! Exiting loop.`);
break; // Terminate loop early
}
}
// 3. Labeled Outer Loop Exit
console.log("
--- Labeled Multi-level Loop Exit ---");
outerMatrixLoop: for (let r = 0; r < 3; r++) {
for (let c = 0; c < 3; c++) {
if (r === 1 && c === 1) {
console.log(`Target found at matrix cell [${r}][${c}]. Exiting outer matrix loop!`);
break outerMatrixLoop; // Exits outer loop directly!
}
console.log(`Processing Cell [${r}][${c}]`);
}
}
break for Search Short-Circuiting: Once a search target is located in a loop, invoke break to save CPU cycles.return.continue in while Loops: Be careful when placing continue inside while loops; ensure the counter increment happens BEFORE the continue statement to avoid infinite loops.What happens if continue is executed in a while loop BEFORE the counter increment line i++?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.