Stop or Skip an Iteration
JavaScript break & continue
`break` exits the loop early. `continue` skips to the next iteration. Both work in any loop.
What you'll learn
- Bail out of a loop with `break`
- Skip an iteration with `continue`
- Know that these don't work in `forEach`
Two keywords let you alter the flow inside any loop:
break— exit the loop immediately.continue— skip the rest of THIS iteration; go to the next.
Both work in for, for..of, for..in, while, and do..while.
break — Exit Early
const numbers = [3, 7, 12, 4, 9, 15, 8];
for (const n of numbers) {
if (n > 10) {
console.log(`First over 10: ${n}`);
break;
}
}
// "First over 10: 12" Note: for “find first match”, numbers.find((n) => n > 10) is even
cleaner. Use break when the logic is more complex or when you need
side effects.
continue — Skip This One
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) continue; // skip odd
console.log(i);
}
// 2, 4, 6, 8, 10 continue is often equivalent to wrapping the rest of the body in
an if. Pick whichever reads better — many prefer the early-exit
style of continue.
They Don’t Work In forEach
forEach calls a function for each item. break and continue are
loop control, so they have nothing to break out of inside forEach.
const numbers = [1, 2, 3, 4, 5];
// This would throw a SyntaxError:
// numbers.forEach((n) => { if (n > 3) break; console.log(n); });
// Use for..of instead:
for (const n of numbers) {
if (n > 3) break;
console.log(n);
}
// 1, 2, 3 If you need early exit, use for..of (or some() / every() /
find() — these stop early by design).
Labels (Rarely Useful)
break only exits the innermost loop. To break out of an outer loop,
you can label it:
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outer;
}
console.log(i, j);
}
}
// 0 0, 0 1, 0 2, 1 0 Up Next
What makes something work with for..of? The iterable protocol.