When writing programs, you may need to modify the standard behavior of loops. This can include finishing their execution earlier or skipping some iterations. To achieve this flexibility, you can use two operators: break and continue. In this topic, we will learn how to work with these operators.
Break operator
The loop execution usually ends when its condition becomes false, but the break operator allows you to exit the loop at any moment you need. Consider the code sample:
for (let n = 1; n <= 50; n++) {
if (n == 5) {
break;
}
console.log(n); // 4
}
In the example above, we've created a counter that had to return values between 1 and 50. However, it does not happen because we have set a condition to exit the loop using the break operator. It breaks the loop after five iterations.
The break operator has two applications:
- It terminates the current loop of any type (
for,while,do-while); - It terminates a case in the
switchstatement;
The break operator is often applied when a loop cannot be executed for some reason, such as when the application detects an error. In other cases, it can end running processes, such as exiting a game or a program.
Continue operator
The continue operator allows you to stop the current loop iteration and start a new one.
This operator can be used inside any loop:
- Inside the
whileordo-whileloop, it returns directly to the loop condition; - Inside the
forloop, it first calculates the increment expression and then returns to the condition.
Use it if you know nothing else to do on the current loop iteration. The following code will print all the even numbers from 1 to 10 into the console:
for (let n = 1; n <= 10; n++) {
if (n % 2 !== 0) {
continue;
}
console.log(n); // 2 4 6 8 10
}
break and continue with the ? operator because such constructions lead to errors.Conclusion
Understanding how to modify the standard behavior of loops is an essential skill for any programmer. By using the break and continue operators, you can add flexibility to your code and achieve more efficient execution.
The break operator allows you to exit a loop prematurely, while the continue operator lets you skip to the next iteration.
By mastering these operators, you can write more complex and sophisticated programs that handle various situations and scenarios.