Break and continue

JavaScript provides control statements that help manage how loops and conditions behave. Two important statements used inside loops are break and continue. These statements allow developers to control the flow of execution more efficiently.

Understanding Break Statement

The break statement is used to stop a loop completely when a specific condition is met. Once break is executed, the loop ends immediately and the program continues with the next part of the code.

Example of Break

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

In this example, the loop stops when the value of i becomes 5. The output will display numbers from 1 to 4 only.

Understanding Continue Statement

The continue statement is used to skip a specific iteration of a loop. Instead of stopping the loop, it moves to the next iteration.

Example of Continue

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

In this example, when i is 3, the loop skips that iteration. The output will display 1, 2, 4, and 5.

Key Differences Between Break and Continue

Break stops the entire loop execution
Continue skips only one iteration and continues the loop
Break exits the loop completely
Continue keeps the loop running

When to Use Break and Continue

Use break when you want to stop a loop early based on a condition
Use continue when you want to skip certain values but continue looping

Practical Use Cases

Stopping a search when a result is found
Skipping invalid or unwanted data during processing
Improving performance by avoiding unnecessary iterations

Conclusion

Break and continue statements are essential for controlling loops in JavaScript. They help make code cleaner, more efficient, and easier to manage.

Home ยป JavaScript Fundamentals (Beginner Level) > Loops > break and continue