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:

const list = ['a', 'b', 'c'];
for (let i = 0; i < list.length; i++) {
  if (list[i] === 'b') break;
  console.log(list[i]);
}

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:

const list = ['a', 'b', 'c'];
for (const item of list) {
  if (item === 'b') break;
  console.log(item);
}

Similarly, the break keyword can be employed in while loops. Consider the following code snippet:

const list = ['a', 'b', 'c'];
let i = 0;
while (i < list.length) {
  if (list[i] === 'b') break;
  console.log(list[i]);
  i++;
}

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:

const list = ['a', 'b', 'c'];
for (const item of list) {
  if (item === 'b') continue;
  console.log(item);
}

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.