How to Exit a forEach Loop Early in JavaScript?

Estimated read time 2 min read

In JavaScript, you can exit a forEach loop early using the return statement. The return statement is used to exit a function, and when used inside a forEach loop, it will exit the loop.

Here’s an example of how to exit a forEach loop early in JavaScript using the return statement:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => {
  if (number === 3) {
    return; // exit the loop when number is equal to 3

In this example, a forEach loop is used to iterate over an array of numbers. The loop contains an if statement that checks whether the value of number is equal to 3. If number is equal to 3, the return statement is executed, causing the loop to exit early. If number is not equal to 3, the loop continues and the value of number is printed to the console.

It’s worth noting that the return statement can also be used with other types of loops, such as for and while loops. Additionally, you can use a labeled return statement to exit nested loops, by specifying the label of the outer loop that you want to exit. However, in the case of forEach loop, it is not possible to exit the outer function using return.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply