🏷️ break only breaks inner loop
Need to exit nested loops? Labeled statements break or continue outer loops. Perfect for search in matrix.
❌ Without Label (Cannot break outer)
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (found) {
break; // Only breaks inner loop
}
}
}
// Outer loop continues!
✅ With Label (Break outer)
outer: for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (found) {
break outer; // Breaks both loops!
}
}
}
🎯 Real-World Examples
// Search in 2D array
function findValue(matrix, target) {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === target) {
console.log(`Found at (${i}, ${j})`);
return; // return works too
}
}
}
}
// Continue outer loop
outer: for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (shouldSkipRow) {
continue outer; // Skip to next i
}
}
}
💡 Use Cases
- Matrix search (find value in 2D array)
- Nested loops with early exit condition
- Parsing complex nested structures
- Game development (collision detection)
"Nested loops, found what I needed. break only exited inner loop. Added label, break outer. Code worked. Labels are rare but essential when needed."

