Course contentsShow
← JavaScript
Lesson 333 of 2,7239. Control FlowFree lesson

Labels with Blocks (Not Just Loops)

Using labels on plain block statements to enable early exits with break, creating named scopes.

Labels with Blocks (Not Just Loops)

You'll learn how to use labels on plain block statements to create named scopes you can break out of early.

Beyond Loops

So far, you've seen labels used with loops to break out of nested iterations. But here's a lesser-known fact: you can label any block statement, not just loops. This creates a named scope that you can exit early using break.

Creating Named Scopes

A labeled block looks like this:

myBlock: {
  console.log("Start of block");
  
  if (someCondition) {
    break myBlock; // Exit the entire block early
  }
  
  console.log("This won't run if we broke out");
}

console.log("After the block");

Think of it like creating a chapter in a book that you can skip to the end of instantly. The label gives the block a name, and break lets you jump to its closing brace.

Practical Use Cases

This pattern is useful when you have complex logic with multiple early-exit conditions:

validation: {
  if (!username) {
    error = "Username required";
    break validation;
  }
  
  if (username.length < 3) {
    error = "Username too short";
    break validation;
  }
  
  error = null; // All checks passed
}

if (error) {
  console.log(error);
}

This avoids deeply nested if-else chains while maintaining clarity about what you're exiting.

Important Limitations

Remember: you can only use break with labeled blocks, not continue (which is loop-specific). And the label must be directly attached to the block you want to exit.

Key Takeaway: Labels work on any block statement, creating named scopes you can exit early with break, offering an alternative to nested conditionals in complex logic.