Common Patterns: Matrix Search and Multi-Level Break
You'll learn: How labeled statements elegantly solve the real-world problem of searching through 2D arrays (matrices) and exiting immediately when a match is found.
The Matrix Search Problem
Imagine searching through a grid of data—maybe seats in a theater, cells in a spreadsheet, or pixels in an image. When you find what you're looking for, you want to stop immediately, not just exit the inner loop but abandon the entire search.
Without labels, you'd need clunky workarounds like flag variables or wrapping everything in a function to use return.
The Labeled Break Solution
Labeled statements shine here:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let target = 5;
let found = false;
outerLoop: for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] === target) {
console.log(`Found ${target} at row ${row}, col ${col}`);
found = true;
break outerLoop; // Instantly exits BOTH loops
}
}
}
if (!found) {
console.log(`${target} not found`);
}
Without break outerLoop, you'd only exit the inner loop and keep checking remaining rows pointlessly.
The Pattern Explained
The pattern is simple: label the outermost loop, then break to that label when your condition is met. This avoids extra state variables tracking whether to continue or messy logic between loops. For matrix searches, validation checks, or any nested traversal where you need a clean "abort mission" button, this is your tool.
Key Takeaway: Labeled breaks turn awkward nested loop exits into clean, direct solutions—especially powerful for 2D array searches where finding one match means you're done searching.