Mark As Completed Discussion

Break and Continue Statements

In programming, there are situations where we need to control the execution of loops based on certain conditions. The break and continue statements allow us to have more control over the flow of loops.

The break Statement

The break statement is used to terminate the loop and exit its current iteration. When the break statement is encountered inside a loop, the loop is immediately terminated, and the program continues with the next statement after the loop.

Here's an example that demonstrates the usage of the break statement:

JAVASCRIPT
1for (let i = 1; i <= 10; i++) {
2  if (i === 5) {
3    break;
4  }
5  console.log(i);
6}

In this example, the loop will iterate from 1 to 10. However, when i becomes equal to 5, the break statement is executed, and the loop is terminated. As a result, only the numbers 1, 2, 3, and 4 will be logged to the console.

The break statement is useful when we want to exit a loop prematurely based on a certain condition.

The continue Statement

The continue statement is used to skip the rest of the current iteration and move on to the next iteration of the loop. When the continue statement is encountered inside a loop, the remaining statements inside the loop for that iteration are skipped, and the program continues with the next iteration.

Here's an example that demonstrates the usage of the continue statement:

JAVASCRIPT
1for (let i = 1; i <= 10; i++) {
2  if (i % 2 === 0) {
3    continue;
4  }
5  console.log(i);
6}

In this example, the loop will iterate from 1 to 10. However, when i is an even number (divisible by 2), the continue statement is executed, and the remaining statements inside the loop are skipped for that iteration. As a result, only the odd numbers 1, 3, 5, 7, and 9 will be logged to the console.

The continue statement is useful when we want to skip certain iterations of a loop based on a certain condition.

Both the break and continue statements provide us with more control over the flow of loops in JavaScript. They can be used to handle specific cases and make our code more efficient and readable.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment