Ways to Terminate Loops in JavaScript
Introduction
In JavaScript, loops are essential for executing a block of code repeatedly. However, sometimes we need to break out of a loop prematurely or skip an iteration. In this article, we will explore different ways to terminate loops in JavaScript.
The break Keyword
The break keyword allows us to exit a loop instantly, irrespective of the loop condition. This works for for, for..of, and while loops. Let’s consider an example:
1 | const list = ['a', 'b', 'c']; |
In the above code, when list[i] is equal to 'b', the loop breaks, and the remaining iterations are skipped.
The break keyword can also be used in for..of loops to exit prematurely. Here’s an example:
1 | const list = ['a', 'b', 'c']; |
Similarly, the break keyword can be employed in while loops. Consider the following code snippet:
1 | const list = ['a', 'b', 'c']; |
The continue Keyword
The continue keyword allows us to skip an iteration and proceed to the next one. It is primarily used with for, for..of, and while loops. Unlike break, continue does not terminate the loop but simply skips the current iteration. Let’s illustrate this with an example:
1 | const list = ['a', 'b', 'c']; |
In the code above, when item is equal to 'b', the loop skips that iteration and moves on to the next one.
Conclusion
In JavaScript, we have two essential keywords for terminating loops: break and continue. The break keyword allows us to exit a loop altogether, while the continue keyword lets us skip a particular iteration. Understanding when and how to use these keywords can greatly enhance the control flow of our code.
tags: [“JavaScript”, “loops”, “break”, “continue”]