Sub topic 9
Exiting and Skipping: break, continue, and Labels
This chapter assumes you can write a classic for loop and a while loop, and that you know how if statements and block scoping with let work. Every loop you have written so far stops in one place only: when its condition turns false. Real loops often need more exits. A search should stop once it finds its match, and a filter should skip bad records without wrapping the whole body in an if. In nested loops, you sometimes need to leave every level at once. JavaScript gives you three tools for this: break, continue, and labels.
What break and continue actually do
break ends the innermost enclosing loop (or switch) right away. Control jumps to the first statement after that loop.
continue ends only the current iteration. The rest of the body is skipped, and the loop goes on to its next step. In a for loop, that next step is the update expression (i++) followed by the condition test. In a while or do...while loop, it is the condition test alone.
Notice in the diagram that continue and reaching the end of the body lead to the same place. continue is an early "end of body," and it does not skip the update.
Stopping early with break
The most common use of break is a search. Once you have the answer, more iterations waste time and can overwrite the result.
const readings = [12, 7, -3, 9, -1];
let firstNegativeIndex = -1;
for (let i = 0; i < readings.length; i++) {
if (readings[i] < 0) {
firstNegativeIndex = i;
break;
}
}
console.log(firstNegativeIndex); // 2Without the break, the loop would keep going and record index 4, the last negative value. That is a quiet logic bug, and nothing would throw an error.
break is also the usual way out of a loop that is meant to run until something happens inside it:
const queue = ["job1", "job2", "STOP", "job3"];
let pos = 0;
while (true) {
const item = queue[pos++];
if (item === undefined || item === "STOP") break;
console.log("processing", item);
}
// processing job1
// processing job2while (true) with a break is fine when the exit test fits most naturally in the middle of the body. Keep the break easy to see, ideally near the top of the body. A reader should not have to hunt for the only way out.
Skipping an iteration with continue
continue lets you reject unwanted items at the top of the body, so the main logic is not nested inside an if:
const orders = [
{ id: 1, status: "paid", total: 40 },
{ id: 2, status: "cancelled", total: 99 },
{ id: 3, status: "paid", total: 15 },
];
let revenue = 0;
for (let i = 0; i < orders.length; i++) {
const order = orders[i];
if (order.status !== "paid") continue;
revenue += order.total;
}
console.log(revenue); // 55This is the loop version of a guard clause. Each continue names one reason to skip, and the code after it can assume that every check passed.
The continue trap in while loops
A for loop's update expression runs even after continue. A while loop has no update expression, so you must advance the counter yourself, and continue can jump over that line:
// BUG (do not run): i never increments once it reaches 2
// let i = 0;
// while (i < 5) {
// if (i === 2) continue;
// console.log(i);
// i++;
// }
// Fixed: advance before any continue can skip it
let i = 0;
while (i < 5) {
i++;
if (i % 2 === 0) continue;
console.log(i);
}
// 1
// 3
// 5Labels: targeting an outer loop
Plain break and continue only affect the innermost loop. In nested loops, that is often the wrong one. A label is an identifier followed by a colon, placed before a statement. break label and continue label then act on the labeled statement instead of the innermost loop.
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) continue;
if (i * j === 2) break outer;
console.log(i, j);
}
}
// 0 0
// 0 2
// 1 0Trace it. When i is 0, j = 1 is skipped by the plain continue, which affects only the inner loop. When i is 1 and j is 2, the product is 2, and break outer ends both loops. The outer loop never reaches i = 2.
continue label jumps to the next iteration of the outer loop. This is useful when one bad value should throw away a whole row:
const rows = [[1, 2], [0, 5], [3, 4]];
const sums = [];
nextRow: for (let r = 0; r < rows.length; r++) {
let sum = 0;
for (let c = 0; c < rows[r].length; c++) {
if (rows[r][c] === 0) continue nextRow;
sum += rows[r][c];
}
sums.push(sum);
}
console.log(sums); // [3, 7]The row containing 0 never reaches sums.push, because continue nextRow skips the rest of the outer body.
Labeled blocks
break with a label works on any labeled block, not only loops. This gives you an early exit from a sequence of checks without writing a function:
const user = { name: "Ada", email: "" };
check: {
if (!user.name) {
console.log("missing name");
break check;
}
if (!user.email) {
console.log("missing email");
break check;
}
console.log("user is valid");
}
console.log("done");
// missing email
// donecontinue cannot target a labeled block, because a block has no "next iteration." Labeled blocks are legal but rare in real code. In most cases, a small function with early returns says the same thing more clearly.
Rules and errors
| Statement | Allowed inside | Effect |
|---|---|---|
| `break` | loop or `switch` | Exits the innermost loop or `switch` |
| `break label` | any labeled statement that encloses it | Exits that labeled statement |
| `continue` | loop | Starts the next iteration of the innermost loop |
| `continue label` | labeled loop that encloses it | Starts the next iteration of that loop |
Violations are SyntaxErrors caught before any code runs:
breakwith no label outside a loop orswitch.continueoutside a loop, orcontinue labelwhere the label marks a non-loop statement.- A label that does not enclose the
breakorcontinue, including a label outside the current function.
That last rule matters for callbacks. Labels and break cannot cross a function boundary:
// SyntaxError: the arrow function is a separate function body
// [1, 2, 3].forEach((n) => {
// if (n === 2) break;
// });Inside a forEach callback, return only ends that one call, so it acts like continue, not break. To stop early, use a real loop or a method that stops on its own, such as some or find. Those methods are covered in a later chapter.
Interaction with try...finally
If you break or continue out of a try block, its finally block still runs first:
for (let i = 0; i < 3; i++) {
try {
if (i === 1) break;
console.log("body", i);
} finally {
console.log("cleanup", i);
}
}
// body 0
// cleanup 0
// cleanup 1Cleanup code is therefore safe even when a loop exits early. One caution: a break or return written inside finally replaces whatever exit was already happening, including a thrown error. Keep jump statements out of finally blocks.
Choosing between labels and alternatives
Labels are useful, but many teams rarely use them, and some readers will not recognize them. Before you reach for one, consider these options:
- Extract a function and
return. A nested search becomesfunction findCell(grid, target) { ... return [r, c]; ... return null; }. Thereturnleaves every loop at once, and the function name explains the intent. - Use a flag only as a last resort. Setting
found = trueand checking it in the outer condition works, but it spreads one decision across several lines. - Use a label when the loops share many local variables that would be awkward to pass into a function, or when performance-sensitive code should stay inline.
Name labels after what they do (nextRow, search) rather than outer, so that continue nextRow reads as a sentence.
Exercise
This loop is meant to log the odd numbers from 1 to 9, but it hangs. Explain why and fix it. let n = 0; while (n < 10) { if (n % 2 === 0) continue; console.log(n); n++; }
Show answer
When n is 0, the condition n % 2 === 0 is true, so continue jumps back to the loop test without reaching n++. n stays 0 forever. Fix it by moving the increment above the continue: while (n < 10) { n++; if (n % 2 === 0) continue; console.log(n); }. This logs 1, 3, 5, 7, 9. You could also rewrite it as for (let n = 1; n < 10; n++) { if (n % 2 === 0) continue; console.log(n); }.
Exercise
What does this code print, and why? search: for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { if (j > i) continue search; console.log(i, j); } }
Show answer
It prints "1 1", "2 1", "2 2", "3 1", "3 2", "3 3". Each time j becomes greater than i, continue search abandons the rest of the inner loop and moves the outer loop to its next i. Each row therefore prints j values only up to i.
Exercise
Rewrite this nested search so it uses neither a label nor a flag variable, and returns the position of target as [row, col], or null if target is missing. const grid = [[4, 8], [15, 16], [23, 42]];
Show answer
Extract a function and return from inside the inner loop: function findCell(grid, target) { for (let r = 0; r < grid.length; r++) { for (let c = 0; c < grid[r].length; c++) { if (grid[r][c] === target) return [r, c]; } } return null; } findCell(grid, 16) returns [1, 1], and findCell(grid, 7) returns null. The return statement leaves both loops at once.