TypeScript Reference ยท Keywords and Declarations
Labeled statements in TypeScript
Reference for labeled statements in TypeScript: naming loops and blocks, break label, continue label, nested loops and the allowUnusedLabels option.
A label is an identifier followed by a colon placed in front of a statement. It gives that statement a name that break and continue can target. Without labels these two keywords only affect the innermost loop or switch; with a label they can jump out of, or to the next iteration of, an outer one.
Labels are plain JavaScript, so TypeScript adds no new syntax. It checks that every label you use actually exists around the break or continue, and it can report labels that nothing uses.
outer: for (const row of rows) { for (const cell of row) { if (cell === target) break outer; } }
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
label: statement break label; continue label;
| Part | Description |
|---|---|
label |
Any identifier. Label names live in their own namespace, so they never clash with variables. |
break label |
Leaves the labeled statement. The label may name any enclosing statement, including a plain block. |
continue label |
Jumps to the next iteration of the labeled loop. The label must be on a loop (for, for...of, for...in, while, do...while). |
Using a label that is not in scope is a compile error, and jumping into a label from a nested function is not possible: labels do not cross function boundaries.
Usage notes
- Prefer extracting a function. A
returnfrom a helper usually reads better than a labeledbreak, and it lets TypeScript infer the result type. - Narrowing is flow based. After
break label, the compiler merges the control-flow paths, so variables assigned inside the loop (likefoundabove) areT | undefinedafterwards. continueneeds a loop label.continuepointing at a labeled block is a syntax error.- Unused labels. The
allowUnusedLabelsoption controls whether an unused label is reported; when it isfalsean unused label is an error (TS7028). - Same label name nested twice in one function is an error, but the same name may be reused in sibling statements.
- No
goto. Labels are not jump targets for arbitrary code; they only work withbreakandcontinue. - Style. Use short lowercase names that describe the loop (
outer,rows,nextWord).