DEV Community

Abdul Rahim Shahad
Abdul Rahim Shahad

Posted on

JS Fundamentals - Break VS Continue

Break and Continue are two methods used in Javascript to determine when/where a loop should end or skip an element.

BREAK

Break is used in a loop where we want the loop to cease running. This is most commonly seen in switch statements where a break is usually placed at the end of the final case but it can also be used in other loops such as for loops as well. Below is an example of a break being used in a for loop.
for(let i = 0; i <= 10; i++){
if( i ===7)
console.log('lucky seven');
break;
}

In the above block of code, when the iteration reaches the number 7, "lucky seven" is logged to the console and the loop ends right there.

CONTINUE

Continue is different to break in the sense that it makes the loop skip/jump at the point where a given condition is met. Below is an example of continue used in a for loop.
for(let i = 0; i <= 10; i++){
if(i%2 = 0) continue;
console.log(i)
}

The output of the above block of code will be the odd numbers (1,3,5,7 and 9). This is because continue tells the loop to skip every iteration where i is an even number.

Summary

  1. Break terminates the whole loop wherever it is placed or a condition is met.
  2. Continue skips any iteration where a given condition is met in a loop.

Top comments (0)