0 day streak
javascript / intermediate
Snippet

Labelled Loop Control in Nested Operations

Labeled statements in JavaScript allow you to name a loop and control execution flow across nested loops. Using `break labelName` immediately exits the designated outer loop, eliminating the need for extra boolean flags or multiple break statements.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const matrix = [
[1, 2, 3],
[4, 9, 6],
[7, 8, 5]
];
let targetFound = false;
searchLoop: for (let r = 0; r < matrix.length; r++) {
for (let c = 0; c < matrix[r].length; c++) {
if (matrix[r][c] === 9) {
targetFound = true;
break searchLoop;
}
}
}
console.log(`Target found: ${targetFound}`);
nodejs
Breakdown
1
searchLoop: for (let r = 0; r < matrix.length; r++) {
Attaches the label `searchLoop` to the outer loop statement.
2
break searchLoop;
Immediately terminates the outer loop labeled `searchLoop` instead of just the inner loop.