How to stop forEach() method in JavaScript

How to stop forEach() method in JavaScript:

forEach is used to iterate through an array of items. For example:

var values = [1, 2, 3, 4, 5, 6, 7, 8];

values.forEach((item, index) => {
  console.log(values[index]);
});

It will print:

1
2
3
4
5
6
7
8

forEach method calls the function for each item with its index. It is bit tricky to stop forEach in between, e.g. if we want to stop it once it reaches 5, it is not that easy. break doesn’t work here. We can solve it with a different approach. In this post, I will show you two different ways to stop forEach with example.

Using a flag :

We can use a flag to stop the iteration of the loop. It will not exit from the loop, but skip the last elements of the loop. For example,

var values = [1, 2, 3, 4, 5, 6, 7, 8];

values.forEach(function iterateItems(item, index) {
  if (iterateItems.stop) {
    return;
  }

  if (item == 5) {
    iterateItems.stop = true;
  }

  console.log(values[index]);
});

If the current iterating element is 5, we are assigning one flag stop as true. On next iteration, it is returning if the value of stop is true. So, it skips all other elements after 5.

By throwing an Exception:

We can also use a try-catch block and throw an Exception in the try block. It will exit the loop and move to the catch block. For example:

var values = [1, 2, 3, 4, 5, 6, 7, 8];

try {
  values.forEach(function iterateItems(item, index) {
    if (item > 5) {
      throw new Exception("Limit reached");
    }

    console.log(values[index]);
  });
} catch (e) {
  console.log("Loop completed !");
}

It will print:

1
2
3
4
5
Loop completed !

It exits once it reaches 6.

This method is more efficient than the previous one because it exits from the loop, the first method keeps the loop running.

You might also like: