Two keywords give you finer control over a loop.
break: stop the loop
const numbers = [4, 8, 15, 16, 23, 42];
for (const n of numbers) {
if (n > 15) {
console.log("First number above 15:", n);
break;
}
}
When break runs, the loop ends immediately and the code after it continues. It is perfect for “stop when you find what you were looking for”.
continue: skip this round
continue jumps straight to the next round, skipping the rest of the body.
for (let i = 1; i <= 6; i++) {
if (i % 2 === 0) {
continue; // skip even numbers
}
console.log(i); // 1, 3, 5
}
In while loops too
let i = 0;
while (i < 10) {
i++;
if (i === 3) continue;
if (i === 6) break;
console.log(i); // 1, 2, 4, 5
}
In a while loop, make sure the update (i++) happens before continue, or you create an infinite loop.
Nested loops and labels
break only leaves the innermost loop. A label lets you leave an outer one. It is rarely needed, but you may see it.
outer: for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
if (row === 1 && col === 1) {
console.log("Found at", row, col);
break outer;
}
}
}
Better alternatives
For arrays, methods often express the intent more clearly than break:
const numbers = [4, 8, 15, 16, 23, 42];
console.log(numbers.find(n => n > 15)); // → 16
console.log(numbers.some(n => n > 40)); // → true
find and some stop at the first match, just like break. See find and findIndex.
Not for forEach
break and continue do not work inside forEach() callbacks. Use a for...of loop, some() or find() instead.