Skip to main content

Break and Continue

The break and continue statements are used to control the flow of loops in JavaScript. They allow you to exit a loop prematurely or skip the current iteration based on certain conditions.

Break Statement

The break statement is used to exit a loop prematurely. When a break statement is encountered inside a loop, the loop is terminated, and the program control moves to the statement immediately following the loop.

Here is the syntax of the break statement:

for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}

In the example above, the break statement is used to exit the loop when the value of i is 3. Therefore, the loop will only print the numbers 1 and 2.

Continue Statement

The continue statement is used to skip the current iteration of a loop and move to the next iteration. When a continue statement is encountered inside a loop, the current iteration is terminated, and the loop proceeds to the next iteration.

Unlike the break statement, the continue statement does not exit the loop entirely; it only skips the current iteration.

Here is the syntax of the continue statement:

for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}

In the example above, the continue statement is used to skip the iteration when the value of i is 3. Therefore, the loop will print all numbers from 1 to 5, except 3.

The break and continue statements are the only JavaScript statements that can alter the flow of loops.

tip
  • The break statement is used to exit a loop prematurely.
  • The continue statement is used to skip the current iteration of a loop and move to the next iteration.
  • The break and continue statements can also be used to jump out of any code block, not just loops.

The best way to get the hang of these statements is to practice using them in different scenarios. These concepts are used in a lot of DSA( Data Structures and Algorithms) problems, so it's essential to understand how they work. They are also used in real-world applications.

In the next sections, we will be dealing with objects

Made with ❤️ by Fasakin Henry