Breaking from nested loops in JavaScript can be tricky, but there are several effective methods to accomplish this task. One commonly used approach is by utilizing labels with the break statement. Here's the example:
<script>
// Define a label for the outer loop
outerLoop: for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (i === 2 && j === 2) {
// Break out of both loops when condition is met
break outerLoop;
}
console.log(`i: ${i}, j: ${j}`);
}
}
</script>
In this example, outerLoop is a label assigned to the outer loop. When the break statement is encountered with the outerLoop label, it breaks out of both the inner and outer loops.
Comments (2)
Instead of labels, you can use a variable to control the loop execution. Set the variable's value to true when you want to break from the loops.
<script>
let shouldBreak = false;
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (i === 2 && j === 2) {
shouldBreak = true;
break;
}
console.log(`i: ${i}, j: ${j}`);
}
if (shouldBreak) {
break;
}
}
</script>
Wrap your nested loops inside a function and use the return statement to exit the function when needed.
<script>
function breakFromLoops() {
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (i === 2 && j === 2) {
return;
}
console.log(`i: ${i}, j: ${j}`);
}
}
}
breakFromLoops();
</script>