JavaScript : Break and Continue

In JavaScript, break and continue are control flow statements used within loops to alter the normal execution of the loop.

1. break Statement:


The break statement is used to terminate the loop immediately when a certain condition is met. It's commonly used to exit a loop prematurely.


for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break; // Terminate the loop when i equals 3
  }
  console.log(i);
}

 

Output:


0
1
2

 

2. continue Statement:


The continue statement is used to skip the current iteration of the loop and continue with the next iteration. It's commonly used to skip certain iterations based on a condition.


for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue; // Skip the iteration when i equals 2
  }
  console.log(i);
}

 

Output:


0
1
3
4

 

Example with break and continue:


let sum = 0;

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue; // Skip the iteration when i equals 2
  }
  if (i === 4) {
    break; // Terminate the loop when i equals 4
  }
  sum += i;
}

console.log(sum); // Output: 3 (sum of 0, 1, 3)
 

In this example, the loop iterates from 0 to 4, but skips the iteration when i equals 2 using continue , and terminates the loop when i equals 4 using break . The sum is calculated for the iterations where continue was not used.