**break** terminates the current loop or switch. With **labeled statements**, break can exit an outer loop from an inner one. Overuse of break creates hard-to-follow control flow — consider restructuring with early returns in functions.
1Understanding break Statement
break terminates the current loop or switch. With labeled statements, break can exit an outer loop from an inner one. Overuse of break creates hard-to-follow control flow — consider restructuring with early returns in functions.
Use a labeled break to exit nested loops: 'outer: for (...) { for (...) { break outer; } }'
// Find the first even number > 10 in a large dataset
const data = [3, 7, 11, 4, 15, 12, 9];
let found = null;
for (const n of data) {
if (n > 10 && n % 2 === 0) {
found = n;
break; // no need to keep searching
}
}
console.log('Found:', found); // 122Practical Example
Here is a real-world application of break Statement showing how it is used in production JavaScript code.
// Labeled break for nested loops
let result = null;
outer: for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (i * j > 6) {
result = { i, j };
break outer; // exits BOTH loops
}
}
}
console.log(result); // { i: 2, j: 4 }3Best Practices
Follow these guidelines when working with break Statement:
1. Use break to exit loops once a target is found
2. Use labeled break for nested loop exits
3. Consider restructuring with functions and return instead
Tip: Use a labeled break to exit nested loops: 'outer: for (...) { for (...) { break outer; } }'
// Find the first even number > 10 in a large dataset
const data = [3, 7, 11, 4, 15, 12, 9];
let found = null;
for (const n of data) {
if (n > 10 && n % 2 === 0) {
found = n;
break; // no need to keep searching
}
}
console.log('Found:', found); // 12