TypeScript Reference ยท Keywords and Declarations
TypeScript break and continue
Reference for break and continue in TypeScript: leaving loops and switches, skipping iterations, labels for nested loops, and how they affect type narrowing.
break leaves the nearest enclosing loop or switch immediately. continue skips the rest of the current loop iteration and jumps to the next one (for a for loop, to the update expression). Both can take a label to target an outer statement.
TypeScript treats them as control-flow edges, so narrowing follows them: after if (x === undefined) continue;, the variable x is narrowed for the remainder of the iteration.
for (const n of [1, 2, 3, 4]) { if (n % 2 === 0) continue; // skip evens if (n > 3) break; // stop entirely }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
break; break label; continue; continue label;
| Part | Description |
|---|---|
break |
Exits the innermost for, while, do...while or switch. |
continue |
Moves to the next iteration of the innermost loop. Not allowed in switch unless a loop surrounds it. |
label |
Names an enclosing statement, declared as label: statement. continue label needs a loop label. |
Errors and edge cases:
breakoutside a loop or switch is error TS1105 ("A 'break' statement can only be used within an enclosing iteration or switch statement").continueoutside a loop is error TS1104.- Jumping to a label that does not enclose the statement is error TS1116 ("A 'break' statement can only jump to a label of an enclosing statement").
- A jump cannot cross a function boundary (TS1107, "Jump target cannot cross function boundary"): inside a callback such as
forEach, a label or loop outside it is out of reach.
Usage notes
forEachcannot be broken. Usefor...of, orsome/everywhen you want early exit with a boolean.- Guard clauses.
continueat the top of a loop body keeps the happy path unnested and narrows in the process. breakinswitch. It prevents fall-through; see switch.- Labels are rarely needed. Prefer extracting the nested loop into a function and using
return. - Narrowing after loops. After a
while (true)loop, code is reachable only through abreak, and TypeScript narrows accordingly. - Finally blocks.
breakandcontinueinsidetryrun thefinallyblock first. - Unreachable code. Statements right after
breakorcontinuein the same block are flagged as unreachable.
Related
- for, while, Labeled statements, switch
- Lessons: Narrowing, Arrays and tuples, Functions