JavaScript Breaking Out of Loops


In JavaScript, you can exit from a loop prematurely using control flow statements. This can be useful when you need to stop the execution of a loop based on a specific condition that is not directly related to the loop's continuation condition. Here’s how you can break out of loops:

1. break Statement

The break statement is used to terminate the current loop immediately and exit to the code that follows the loop. It works with for, while, do...while, and switch statements.

Syntax

break;

Example

Here’s an example of using break in a for loop:

for (let i = 0; i < 10; i++) { if (i === 5) { break; // Exits the loop when i is 5 } console.log(i); // Logs: 0, 1, 2, 3, 4 }
  • Explanation:
    • The loop runs until i reaches 5.
    • When i is 5, the break statement is executed, terminating the loop.

2. continue Statement

The continue statement skips the current iteration of the loop and proceeds with the next iteration. It works similarly with for, while, and do...while loops.

Syntax

continue;

Example

Here’s an example of using continue in a for loop:

for (let i = 0; i < 10; i++) { if (i % 2 === 0) { continue; // Skips even numbers } console.log(i); // Logs: 1, 3, 5, 7, 9 }
  • Explanation:
    • The loop skips the console.log statement for even values of i.
    • Only odd values are printed.

3. Labeled Statements

JavaScript also supports labeled statements, which can be used to break out of or continue outer loops from within nested loops. Labeled statements give a loop a name that can be referenced by break or continue.

Syntax

outerLoop: for (let i = 0; i < 3; i++) { innerLoop: for (let j = 0; j < 3; j++) { if (j === 1) { break outerLoop; // Breaks out of the outer loop } console.log('i = ' + i + ', j = ' + j); } }

Example

outerLoop: for (let i = 0; i < 3; i++) { innerLoop: for (let j = 0; j < 3; j++) { if (j === 1) { break outerLoop; // Exits both loops } console.log('i = ' + i + ', j = ' + j); } }
  • Explanation:
    • The break outerLoop; statement exits both the outerLoop and innerLoop when j is 1.
    • It logs i = 0, j = 0 before breaking out of both loops.

Summary

  • break Statement: Exits the current loop immediately, bypassing the remaining iterations.
  • continue Statement: Skips the rest of the current loop iteration and proceeds with the next iteration.
  • Labeled Statements: Allow breaking out of or continuing outer loops from within nested loops.