After this lesson you can stop a loop as soon as you have what you need, skip items you do not want, and escape from a loop inside a loop. This builds on for loops and while and do...while loops.
break: stop right now
Imagine searching a list for the first number divisible by 7. Once you find it, looping over the rest is wasted work. break ends the loop immediately.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const numbers = [12, 25, 33, 49, 56, 70];
let found = null;
for (const n of numbers) {
log("checking", n);
if (n % 7 === 0) {
found = n;
break;
}
}
log("found:", found);
</script>The output is checking 12, checking 25, checking 33, checking 49, then found: 49. The loop never looks at 56 or 70. (If you used % and want a refresher, it is the remainder operator from the operators lesson.)
break also ends a switch case, which you saw earlier in The switch statement. In both cases the meaning is the same: leave the nearest enclosing structure.
continue: skip this one
continue abandons the current pass and jumps to the next one. Use it to ignore items that do not matter, so the main work does not have to live inside a deep if.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const entries = ["Asha", "", "Ravi", " ", "Meera"];
for (const entry of entries) {
if (entry.trim() === "") {
continue;
}
log("Hello,", entry);
}
</script>This prints Hello, Asha, Hello, Ravi and Hello, Meera. The blank entries were skipped. This "guard at the top" style keeps the interesting code at the lowest indentation level, like the early returns in the conditions lesson.
continue and the update step
In a for loop, continue still runs the update (i++) before the next check, so it is safe. In a while loop there is no automatic update. If the increment sits below the continue, it gets skipped and the loop can freeze:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
let i = 0;
while (i < 5) {
i++; // update first, so continue cannot skip it
if (i === 3) continue;
log("i is", i);
}
</script>The output is i is 1, i is 2, i is 4 and i is 5. Moving i++ to the top is the usual remedy. If you move it to the bottom, the loop gets stuck the first time i is 3.
Leaving nested loops with labels
A break only leaves the nearest loop. With a loop inside a loop, that is often not what you want. A label is a name followed by a colon, placed before a loop. break label leaves that specific loop.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
let target = null;
search: for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
log("looking at row", row, "col", col);
if (grid[row][col] === 5) {
target = { row, col };
break search;
}
}
}
log("target:", JSON.stringify(target));
</script>The output ends with looking at row 1 col 1, followed by target: {"row":1,"col":1}. It never visits the third row. Without the label, break would only leave the inner loop and the outer loop would carry on with row 2.
You can also write continue outer; to skip to the next pass of an outer loop. Labels are rare in everyday code. If you find yourself reaching for one often, consider moving the nested loops into a function and using return, which leaves every loop at once and also hands back a result:
function findInGrid(grid, value) {
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
if (grid[row][col] === value) return { row, col };
}
}
return null;
}Functions are the topic of the next section of the course.
break and continue in forEach
break and continue only work directly inside for, while and do...while loops (and break in switch). Inside the function you give to the array method forEach, they are a syntax error, because that function is not the loop. Use a for...of loop when you need to stop early.
Stopping early is about efficiency and clarity
Beyond saving time on large lists, break often makes the intent obvious. A loop that says "stop when you find the first match" is easier to understand than one that quietly keeps going and ignores everything after the match. Likewise, continue is best for filtering out unwanted items at the very top of a loop body, so the rest of the code deals only with items that matter.
Common mistakes
- Expecting break to leave every loop. It leaves the nearest one only. Use a label or a function with
return. continuein a while loop that updates below it. The update is skipped and the loop sticks. Put the update beforecontinue.- Using
breakwherereturnis needed.breakonly leaves the loop; code after the loop still runs. Inside a function,returnends the function too. - Putting
breakoutside any loop.if (x) break;with no enclosing loop is a syntax error. - Over-using continue. Several
continuelines in one body make the flow hard to follow. If you need more than one or two, restructure the conditions. - Forgetting
breakis not needed withreturn. In aswitchinside a function, areturnalready leaves the switch.
Exercise
- Loop over
[3, 8, 15, 22, 40]and log the first number greater than 20, then stop. How many numbers did you look at? - Loop from 1 to 20 and log only the numbers that are not multiples of 3, using
continue. - Using the
gridabove, write labelled loops that find the first even number and log its row and column. Then rewrite it as a function usingreturnand compare the two versions.
Key points
- break ends the nearest loop (or switch) immediately.
- continue skips the rest of the current pass and moves on to the next one.
- In a for loop, continue still runs the update expression; in a while loop you must make sure the counter still changes.
- A label before a loop lets break or continue target an outer loop.
- break and continue do not work inside forEach callbacks; use a for...of loop there.