Back to JavaScript
2026-01-055 min read

Using a labeled break with for loops (JavaScript)

Learn Using a labeled break with for loops (JavaScript) step by step with clear examples and exercises.

Why This Matters

Understanding how to use labeled breaks in JavaScript is crucial for writing cleaner and more efficient code. In situations where you have multiple nested loops or switch cases, labeled breaks can help you exit from the correct loop or case without causing unintended side effects. This lesson will guide you through a practical example of using a labeled break with for loops in JavaScript, along with common mistakes to avoid and practice questions to test your understanding.

The Importance of Labeled Breaks

Labeled breaks enable developers to exit from multiple levels of nested loops or switch cases without causing unintended side effects. They provide a way to create more modular and maintainable code by allowing you to control the flow of execution precisely.

Prerequisites

Before diving into the core concept, it's essential that you have a solid grasp of the following topics:

  1. Basic JavaScript syntax (variables, data types, operators)
  2. Control structures (if/else statements, switch cases)
  3. For loops and while loops
  4. Block scoping (let, const, var)
  5. Understanding the concept of loop hierarchies
  6. Familiarity with arrays and objects in JavaScript

Core Concept

A labeled statement is any statement that is prefixed with an identifier. You can jump to this label using a break or continue statement nested within the labeled statement. In this article, we will focus on using the break statement to exit from multiple loops.

Labeling Statements

To create a labeled statement, you simply need to prefix it with an identifier followed by a colon (e.g., outerLoop:). You can then use this label to control the flow of your code using break or continue statements.

outerLoop: // This is a labeled statement
for (let i = 0; i < 5; i++) {
//...
}
break outerLoop; // Exit the outer loop

Using Labeled Breaks

To use a labeled break, you must first define the label before the for loop you want to exit. Once defined, you can use break followed by the label name to exit the specified loop.

outerLoop:
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // Exit the outer loop when i is 1 and j is 1
}
console.log(`i = ${i}, j = ${j}`);
}
}

Worked Example

Let's consider a more practical example where we need to find the first occurrence of a specific number in a two-dimensional array using labeled breaks:

findNumberInArray(arr, target) {
let row, col;
outerLoop: for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] === target) {
row = i;
col = j;
break outerLoop;
}
}
}
return [row, col];
}

const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const target = 5;
console.log(findNumberInArray(arr, target)); // Output: [1, 1]

In this example, we've defined a function called findNumberInArray that takes an array and a target number as arguments. We use nested for loops to iterate over the array and check if the target number is present in each element. If we find the target number, we store its row and column indices and exit the outer loop using the break statement. Finally, we return the row and column indices as an array.

Common Mistakes

  1. Forgetting to define the label: To use a labeled break, you must first define the label before the for loop you want to exit.
outerLoop: // This is incorrect
for (let i = 0; i < 5; i++) {
//...
}
break outerLoop; // This will throw an error
  1. Misplacing the label: The label must be defined before the loop you want to exit, not after it.
for (let i = 0; i < 5; i++) {
outerLoop: for (let j = 0; j < 3; j++) {
//...
}
}
break outerLoop; // This will throw an error
  1. Naming conflicts: Make sure your label doesn't conflict with any reserved words or variable names in your code.
  1. Trying to jump to a different labeled statement using break or continue: The break and continue statements can only be used to exit or skip iterations within the same loop hierarchy as the labeled statement. If you need to jump to a different part of your code, consider using functions or other control structures like try-catch blocks.

Common Mistakes - Additional Considerations

  1. Not handling edge cases: When working with arrays, it's essential to account for missing rows or columns by either returning an error message or filling in default values.
  1. Overcomplicating solutions: Sometimes developers may try to solve problems using labeled breaks when simpler control structures like nested if statements or functions would suffice. Always consider the readability and maintainability of your code.

Practice Questions

  1. Write a function that finds the smallest number in a two-dimensional array using labeled breaks.
  2. Given an array of objects, write a function that finds the object with the maximum value of a specific property using labeled breaks.
  3. Modify the findNumberInArray function to handle arrays with missing rows or columns gracefully (i.e., without throwing errors).
  4. Write a function that finds all occurrences of a specific number in a two-dimensional array using labeled breaks and returns an array containing the row and column indices for each occurrence.
  5. Create a simple game where the user guesses a secret number between 1 and 100. Use labeled breaks to check if the user's guess is correct, too high, or too low.

FAQ

What happens if I use break inside an if statement?

The break statement will only exit the innermost loop that contains it. If you want to exit a higher-level loop, you should wrap the if statement in another loop with a label and use break on that label.

Can I use labeled breaks with continue statements?

Yes! You can use labeled continues to skip iterations of a specific loop instead of exiting it entirely. Just replace the break keyword with continue.

Is it possible to jump to a different labeled statement using break or continue?

No, the break and continue statements can only be used to exit or skip iterations within the same loop hierarchy as the labeled statement. If you need to jump to a different part of your code, consider using functions or other control structures like try-catch blocks.

Using a labeled break with for loops (JavaScript) | JavaScript | XQA Learn