Skip to the next outer-loop iteration
Nested iteration
JS Puzzles · Const
A label names a loop so nested break or continue can target that loop. It provides structured control flow, not an arbitrary jump mechanism.
A label gives a statement an identifier followed by a colon. A break or continue nested inside that labeled statement can refer to the identifier: break exits the labeled statement, while continue advances a labeled loop. Labels are not general-purpose jumps.
labelName: statementouter: for (const row of [[1, 2], [3, 4]]) {
for (const value of row) {
if (value === 3) continue outer;
console.log(value);
}
}The labeled continue skips the rest of the inner loop and starts the next iteration of the outer loop.
Nested iteration
Nested iteration
A label is an identifier followed by a colon that prefixes a statement. A nested break can exit that labeled statement, and a nested continue can move to the next iteration when the labeled statement is a loop.
Follow-up: Can a labeled break target a non-loop statement? Yes. For example, a labeled block can be exited with break, but continue requires a labeled loop.
The label must contain the break or continue statement lexically. A break label exits the labeled statement and resumes after it; continue label proceeds with the next iteration of the labeled loop.
Follow-up: What happens if the label is outside the statement containing the jump? The program is invalid because the referenced label is not in the required containing statement.
JavaScript labels do not provide arbitrary control flow. They work only with break and continue, so they cannot jump into an unrelated location in the program.
Follow-up: Can a label be attached directly to a const declaration? No; labels apply to statements, so place the declaration inside a block statement.
breakcontinueforwhile