Break, Continue and Labels
break ends a loop immediately, and the program continues after it. continue skips the rest of the current round and moves on to the next one. Together they let a loop stop as soon as it has found what it was looking for, or skip items that don't apply, without wrapping the whole body in an if. Labels extend both to nested loops.
In One Minute
breakleaves the innermost loop (orswitch) right away.continuejumps to the next round; in aforloop, the update still runs.- A label (
outer:) before a loop letsbreak outerorcontinue outeract on that outer loop. - In a function,
returnoften reads better thanbreak, and array methods such asfindandsomereplace many search loops.
break: Stop the Loop
Searching is the classic use: once the item is found, there is no reason to look at the rest.
const payments = [
{ name: "Navika", amount: 120 },
{ name: "Srihitha", amount: 0 },
{ name: "Advitha", amount: 95 },
];
let firstUnpaid = null;
for (const payment of payments) {
console.log("Checking", payment.name);
if (payment.amount === 0) {
firstUnpaid = payment.name;
break;
}
}
console.log("First unpaid:", firstUnpaid);Checking Navika
Checking Srihitha
First unpaid: SrihithaExplanation: the loop stops at Srihitha; Advitha is never checked. The loop here is for...of, which gives each item in turn; it has its own lesson next.
break works in for, for...of, for...in, while and do...while loops, and in switch. It does not work in forEach callbacks, because the callback is a separate function, not a loop body.
continue: Skip One Round
continue skips to the next round. It is useful to filter out items early, keeping the main code unindented:
const fees = [120, 0, 85, -10, 45];
let total = 0;
for (const fee of fees) {
if (fee <= 0) {
console.log("Skipping", fee);
continue;
}
total += fee;
}
console.log("Total:", total);Skipping 0
Skipping -10
Total: 250In a classic for loop, continue still runs the update part (i++). In a while loop, it jumps straight to the condition, so make sure the variable that controls the loop is updated before the continue:
let i = 0;
while (i < 5) {
i++; // update first
if (i % 2 === 0) continue;
console.log("Odd:", i);
}Odd: 1
Odd: 3
Odd: 5Labels for Nested Loops
break and continue act on the innermost loop. To act on an outer loop, put a label (a name followed by a colon) in front of it:
const classes = [
["Navika", "Srihitha"],
["Advitha", "Navika"],
];
const wanted = "Advitha";
search: for (let c = 0; c < classes.length; c++) {
for (let s = 0; s < classes[c].length; s++) {
if (classes[c][s] === wanted) {
console.log(`Found ${wanted} in class ${c + 1}, seat ${s + 1}`);
break search;
}
}
}
console.log("Search finished");Found Advitha in class 2, seat 1
Search finishedExplanation: a plain break would only end the inner loop, and the outer loop would keep going. break search ends both. continue search would skip to the next round of the outer loop.
Labels are rare in everyday code. When you find yourself reaching for one, consider moving the nested loops into a function and using return:
function findSeat(classes, wanted) {
for (let c = 0; c < classes.length; c++) {
for (let s = 0; s < classes[c].length; s++) {
if (classes[c][s] === wanted) return { classNumber: c + 1, seat: s + 1 };
}
}
return null;
}
console.log(findSeat([["Navika"], ["Srihitha", "Advitha"]], "Advitha"));
console.log(findSeat([["Navika"]], "Advitha"));{ classNumber: 2, seat: 2 }
nullArray Methods That Stop Early
Many break loops are searches, and arrays have methods for exactly that. They stop at the first match, like break:
Loop with break that... | Array method |
|---|---|
| finds the first matching item | list.find(test) |
| finds its index | list.findIndex(test) |
| checks if any item matches | list.some(test) |
| checks if every item matches | list.every(test) |
const amounts = [120, 0, 95];
console.log(amounts.find((a) => a === 0));
console.log(amounts.some((a) => a === 0));
console.log(amounts.every((a) => a >= 0));0
true
trueThey are covered fully in the array search lesson.
In Practice
The Fee Tracker processes a list of payment records. It skips blank lines with continue, and stops with break at an END marker, ignoring anything after it:
const lines = ["Navika,120", "", "Srihitha,85", "END", "Advitha,999"];
let total = 0;
let count = 0;
for (const line of lines) {
if (line === "") continue;
if (line === "END") break;
const [name, amount] = line.split(",");
total += Number(amount);
count++;
console.log(`Recorded ${name}: $${amount}`);
}
console.log(`${count} payments, $${total}`);Recorded Navika: $120
Recorded Srihitha: $85
2 payments, $205Common Mistakes
Using break inside forEach. It is a SyntaxError ("Illegal break statement"). Use a for...of loop, or some/find, which stop early.
continue before the update in a while loop. The update never runs, and the loop never ends.
Expecting break to exit all nested loops. It exits one. Use a label, or move the loops into a function and return.
Too many continue statements. Several skips scattered through a long body make the flow hard to follow. Filter the data first (list.filter(...)) and loop over the result.
Practice
Challenge: Loop over the numbers 1 to 20. Skip multiples of 3 with continue, stop the loop entirely when you reach the first number greater than 10 that is a multiple of 7, and print the numbers you kept.
Show solution
const kept = [];
for (let n = 1; n <= 20; n++) {
if (n % 3 === 0) continue;
if (n > 10 && n % 7 === 0) break;
kept.push(n);
}
console.log(kept);[1, 2, 4, 5, 7, 8, 10, 11, 13]Key Takeaways
| Keyword | Effect |
|---|---|
break | Leave the loop now |
continue | Go to the next round |
break label | Leave the labeled outer loop |
return | Leave the whole function (and every loop in it) |
Was this tutorial helpful?