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.

The break statement is a control flow mechanism that immediately terminates the execution of the innermost enclosing loop (for, while, do...while), switch statement, or a specific labeled block. Upon execution, program control is unconditionally transferred to the first statement immediately following the terminated structure.

Syntax

break;
break labelIdentifier;

Unlabeled break

When used without an identifier, break applies strictly to the innermost enclosing loop or switch statement. It halts further iterations or case evaluations and exits the block.
for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break; // Terminates the loop when i strictly equals 3
  }
}
// Control flow resumes here
In a switch statement, it prevents fall-through by terminating the switch block after a matched case executes.
const fruit = 'apple';

switch (fruit) {
  case 'apple':
    console.log('Matched apple');
    break; // Terminates the switch block
  case 'banana':
    console.log('Matched banana');
}
// Control flow resumes here

Labeled break

When appended with an identifier, break terminates the specific enclosing statement associated with that label. This is the only mechanism in JavaScript that allows a break statement to exit an arbitrary block statement that is not a loop or a switch.
outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop; // Terminates the 'outerLoop' statement entirely
    }
  }
}
// Control flow resumes here
Breaking from an arbitrary labeled block:
blockLabel: {
  console.log('Execution starts');
  break blockLabel; // Terminates the blockLabel block
  console.log('This statement is unreachable');
}
// Control flow resumes here

Technical Constraints

  • Lexical Scoping: A break statement must be lexically nested within the loop, switch, or labeled statement it intends to terminate.
  • Function Boundaries: A break statement cannot cross function boundaries. It is impossible to use break inside a callback function to terminate an outer loop (e.g., attempting to break out of an Array.prototype.forEach() iteration).
  • Syntax Errors: Executing an unlabeled break outside of a loop or switch, or executing a labeled break referencing an undefined or non-enclosing label, will throw a SyntaxError during the parsing phase.
Master JavaScript with Deep Grasping Methodology!Learn More