Javascript

In JavaScript, break and continue are control flow statements used in loops to alter the default behavior of the loop execution.

  1. Break Statement:

    • The break statement is used to exit a loop prematurely. When encountered within a loop, it immediately terminates the loop, regardless of the loop condition.
    javascript
    for (var i = 0; i < 5; i++) { if (i === 3) { break; // Exit the loop when i reaches 3 } console.log(i); } // Output: 0, 1, 2
  2. Continue Statement:

    • The continue statement is used to skip the current iteration of a loop and move on to the next iteration. It's typically used to avoid executing certain statements within a loop under specific conditions.
    javascript
    for (var i = 0; i < 5; i++) { if (i === 2) { continue; // Skip iteration when i is 2 } console.log(i); } // Output: 0, 1, 3, 4

In both examples, the loop runs from 0 to 4. However, with the break statement, the loop is terminated when i is equal to 3, while with the continue statement, the loop skips the iteration when i is equal to 2.

These statements provide flexibility and control over loop execution and are commonly used in conjunction with conditional statements to achieve specific behavior within loops.

Thanks for learning