HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Break and Continue

The break and continue statements allow you to "jump" in and out of loops. They are essential for optimizing performance and handling specific data cases during iteration.


The break Statement

The break statement "jumps out" of a loop completely. It stops the loop from running further, even if the loop condition is still true.

for (let i = 0; i < 10; i++) {
  if (i === 3) { break; } // Loop stops completely when i is 3
  console.log(i); // Result: 0, 1, 2
}

The continue Statement

The continue statement "jumps over" one iteration in the loop. If a specified condition occurs, it skips that iteration and continues with the next iteration in the loop.

for (let i = 0; i < 5; i++) {
  if (i === 3) { continue; } // Skips the rest of the code when i is 3
  console.log(i); // Result: 0, 1, 2, 4
}

JavaScript Labels

To break or continue inside nested loops, you can use labels. A label is a name followed by a colon (e.g., loopHome:).

list: {
  console.log("item 1");
  console.log("item 2");
  break list; // Exits the labeled block immediately
  console.log("item 3"); // This won't run
}
Common Use: Labels are rarely used but are very powerful when you need to break an outer loop from inside an inner loop.

Key Points to Remember

  • break: Exits the loop entirely
  • continue: Skips the current iteration and goes to the next one
  • Both work in for, while, and do...while loops
  • break is also mandatory in switch blocks
  • Labels provide a way to control nested loops
  • Use these statements to make your loops more efficient by avoiding unnecessary processing