break & continue
Exit a loop early or skip an iteration.
Syntax
break;
continue;Two keywords give you fine control inside loops:
breakβ stops the loop completely.continueβ skips the rest of the current pass and moves to the next.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Stop searching an array as soon as the target item is found to avoid unnecessary iterations.
- Skip rows with missing required fields when importing a CSV without stopping the whole import.
- Exit a polling loop early when a success condition is met before the timeout expires.
More examples
break to exit a loop early
Stops iterating as soon as the target user is found, avoiding processing the remaining elements.
const users = ["alice", "bob", "carol", "dan"];
for (const user of users) {
if (user === "carol") {
console.log("Found:", user);
break;
}
}continue to skip an iteration
Uses continue to skip rows with an empty name field and processes only valid rows.
const rows = [{ name: "A", value: 10 }, { name: "", value: 5 }, { name: "C", value: 8 }];
for (const row of rows) {
if (!row.name) continue; // skip rows with no name
console.log(row.name, row.value);
}break with a while poll loop
Uses an infinite while loop with break to exit as soon as a simulated success condition is met.
let attempts = 0;
while (true) {
attempts++;
const success = attempts === 3; // simulate success on 3rd try
if (success) {
console.log("Succeeded on attempt", attempts);
break;
}
}
Discussion