Back to all posts

Break and Continue


In JavaScript, the break and continue statements are used to control the flow of loops. They allow you to alter the execution of a loop on certain conditions.

Break Statement

The break statement is used to terminate a loop or a switch statement. When a break statement is encountered, the loop or switch statement is immediately terminated, and the program control moves to the next statement after the loop or switch.

Example of using the break statement in a for loop:

for(for i = 0; i < 10; i++) {
    if(i === 5) {
       break;
    }
    console.log(i);
}

console.log('End')

In this example, the loop will terminate when i is equal to 5, and the console will only log number 0 throgh 4. The output will be:

0
1
2
3
4
End

The break statement can also be used with a labeled statement to break out of a nested loop. Here’s an example:

outerloop: for (let i = 0; i < 3; i++) {
  innerloop: for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerloop;
    }
    console.log(`i = ${i}, j = ${j}`);
  }
}

In this example, when i is equal to 1 and j is equal to 1, the break statement is encountered, and the outer loop is immediately terminated. The output will be:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0

Continue Statement

Then continue statement is used to skip the current iteration of a loop and move to the next iteration. When a continue statement is encountered, the code inside the loop for the current iteration is skipped, and the loop moves on the next iteration.

Here’s an example of using the continue statement in a while loop:

let sum = 0;
while (sum < 10) {
  if (sum === 5) {
    console.log(`Loop continue at sum = ${sum}`);
    sum += 1; // This line is added to increment 'sum' even when it's 5.
    continue;
  }
  sum += 1;
}

In this example, when sum become equal to 5, the continue statement is encountered, and the current iteration of the loop is immediately skipped.

Loop continue at sum = 5

The continue statement can also be used with a labeled statement to continue a specific loop. Here’s an example:

loop1: for (let i = 0; i < 3; i++) {
  loop2: for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      continue loop1;
    }
    console.log(`i = ${i}, j = ${j}`);
  }
}

In this example, when i is equal to 1 and j is equal to 1, the continue statement is encountered, and the current iteration of the outer loop is skipped. The output will be:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0

It’s worth noting that the break and continue statements can also be used with labeled statements. Labeled statements allow you to specify the exact loop or switch statement that you want to break or continue. This can be useful when working with nested loops or switch statements.