Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A labeled statement provides a distinct identifier to a statement or block of code, enabling precise control flow manipulation when used in conjunction with break or continue directives. It allows execution to jump out of, or proceed to the next iteration of, a specific enclosing structure, bypassing the default behavior of targeting only the immediately enclosing loop or switch.

Syntax

labelIdentifier: statement
  • labelIdentifier: Any valid JavaScript/TypeScript identifier that is not a reserved word.
  • statement: The code block or loop being labeled.

Control Flow Mechanics

Labeled statements alter the target of control flow directives:
  1. break labelIdentifier; Terminates the execution of the labeled statement and transfers control to the statement immediately following it. While break typically only applies to loops and switch statements, a labeled break can be applied to any labeled block statement.
outerBlock: {
    console.log("Entering block");
    if (true) {
        break outerBlock; // Exits 'outerBlock' immediately
    }
    console.log("Unreachable code");
}
  1. continue labelIdentifier; Terminates the current iteration of the labeled loop and evaluates the loop’s condition for the next iteration. Unlike break, a labeled continue can only be applied to iterative statements (for, while, do...while).
outerLoop: for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
        if (j === 2) {
            continue outerLoop; // Skips remaining inner loop, advances 'i'
        }
    }
}

Technical Constraints and Scope

  • Namespace Isolation: Labels reside in a dedicated namespace. A label identifier can share the exact same name as a variable or function in the same scope without causing a naming collision.
const foo = 10;
foo: for (let i = 0; i < foo; i++) { // Valid TS syntax
    break foo;
}
  • Lexical Boundaries: The scope of a label is strictly limited to the statement it prefixes. Control flow cannot cross function boundaries; a break or continue cannot reference a label situated outside of its immediate enclosing function, including arrow functions or callbacks.
loopLabel: for (let i = 0; i < 3; i++) {
    setTimeout(() => {
        // break loopLabel; // TS Error: Undefined label 'loopLabel'
    });
}
  • Duplicate Identifiers: TypeScript throws a syntax error if overlapping (nested) statements share the same label identifier. However, identical labels are permitted if their scopes are entirely disjointed.
  • Strict Mode Restrictions: Because TypeScript modules execute in strict mode by default, certain identifiers like let, static, yield, and await are strictly prohibited from being used as label names.
Master TypeScript with Deep Grasping Methodology!Learn More