Loops
continue in a loop
Skips the rest of the current loop step and moves on to the next one.
Why it exists
Loops often meet items that don't need processing: empty lines in a file, deleted messages, zeros in a sudoku. You could wrap all the processing in an if, but then the main code drifts right under a layer of nesting. continue lets you say at the start of a step "skip this one" and write the processing without extra indentation. It's the same "early exit" technique as return in functions, just for one step of a loop.
Where it's used
- Skip empty lines when parsing a file or text.
- Don't process hidden, deleted or draft records.
- Skip empty cells on a game board — like the zeros in the sudoku challenge.
- Skip items that failed a check and process the rest.
Syntax
for (...) {
if (skip) continue;
// processing
}Examples
const shown = [];
for (const n of [1, -2, 3]) {
if (n < 0) continue;
shown.push(n);
}
shown; // → [1, 3]const lines = ["milk", "", "bread", ""];
const list = [];
for (const line of lines) {
if (line === "") continue;
list.push(line);
}
list; // → ["milk", "bread"]const found = [];
for (const n of [4, 7, 9, 2]) {
if (n === 9) break;
found.push(n);
}
found; // → [4, 7] — break stopped the whole loopbreak stops the loop entirelyResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
On continue, the loop abandons the current step: the code below it in the body doesn't run. In a counting for, the step (i++) runs next and the condition is checked; in for...of the loop takes the next item.
That's how continue differs from break, which ends the whole loop, and from return, which ends the whole function.
continue works only inside loops. You can't use it in a forEach callback — there you write return, which ends the current callback call.
Traps
How it differs from…
array.filter()If the goal is an array without the unwanted items, filter says it more briefly.
continuefits when the loop does something else as well.