break and continue are two statements that change the normal flow of a loop from the inside. They work inside for loops, while loops, and switch statements, and understanding the difference between them is essential once your loops get more complex than a simple counter.
break: Exit the Loop Entirely
break immediately stops the loop altogether — execution jumps to the first line of code after the loop, and no further iterations happen, even if the loop's condition would otherwise still be true.
const numbers = [4, 9, 15, 23, 8, 2];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 20) {
console.log(`Found it: ${numbers[i]} at index ${i}`);
break; // stop searching once found
}
}
console.log("Search finished.");
Output:
Found it: 23 at index 3
Search finished.
This is a common pattern for searching: once you've found what you're looking for, there's no reason to keep checking the rest of the array.
continue: Skip to the Next Iteration
continue is less drastic — it skips the rest of the current iteration's code and jumps straight to the next one, without exiting the loop entirely.
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) {
continue; // skip odd numbers
}
console.log(i);
}
Output:
2
4
6
8
10
Here, every odd number triggers continue, so the console.log line is skipped for it — but the loop keeps going instead of stopping.
Labeled Loops for Breaking Out of Nested Loops
A plain break only exits the innermost loop it's inside. If you need to break out of an outer loop from within a nested one, you can label the outer loop and reference that label.
outer: for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outer; // exits BOTH loops, not just the inner one
}
console.log(`i=${i}, j=${j}`);
}
}
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Labeled breaks are rare in everyday code and can hurt readability if overused, but they're worth recognizing when you see them in a nested search or grid-processing algorithm.
