JavaScript

Break out of forEach loop in JavaScript

In this post, we’ll see how to break foreach loop in JavaScript.

Let’s say we have these fruits and we want to print all fruits until we see an Avacado.

["🍎", "🍌", "🍊", "🥑", "🍉"]

We could try something like this with the forEach function to break out with a return statement.

["🍎", "🍌", "🍊", "🥑", "🍉"].forEach(fruit => {
  if (fruit === "🥑") {
    return false;
  }
  console.log(fruit)
});

But, this will print watermelon too, and any other items after the avocado. The return statement here in the forEach is just to ignore the current iteration.

A couple of workarounds

  1. Throwing an error in .forEach loop
  2. A flag to ignore

1. Throwing an error in .forEach

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
fruits.forEach(fruit => {
  console.log(fruit);
  if (fruit === "🥑") {
    throw new Error();
  }
});

We print all the fruits until we see an avocado and if we do throw an error.

Ideally, this is not recommended (why would someone throw an error just for the sake of exiting a loop) but it just works.

2. A flag to ignore

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
let fruitFound = false;
fruits.forEach(fruit => {
  if (fruitFound) return;
  
  console.log(fruit);
  if (fruit === "🥑") {
    fruitFound = true;
  }
});

Here we maintain a flag to see if the fruit is found. Once we get to the fruit we will just ignore the rest of the code execution.

The output shows until avocado.

But, there’s a downside to this approach. The loop runs for all the fruits except that it won’t process the rest of the code in the forEach loop. So, for every fruit, the loop is executed irrespective of whether the fruit is found or not.

There is no best way to exit a forEach loop.

Alternatives to using .forEach

There are a handful of alternatives to using .forEach loop. Here are the following alternatives.

  • for..of (use a break; to exit)
  • for..in (use a break; to exit)
  • for loop (use a break; to exit)
  • while (use a break; to exit)
  • every()
  • some()

for..of

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
for (const fruit of fruits) {
  console.log("fruit name " + fruit);
  if (fruit === "🥑") break;
}

for..in

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
for (const fruit in fruits) {
  console.log(fruits[fruit]);
  if (fruits[fruit] === "🥑") break;
}

for loop

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
for (let idx = 0; idx < fruits.length; idx++) {
  console.log(fruits[idx]);
  if (fruits[idx] === "🥑") break;
}

while loop

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
let index = 0;
while (index < fruits.length) {
  console.log(fruits[index]);
  if (fruits[index] === "🥑") {
    break;
  }
  index++;
}

.every()

Unlike the previous loops, which used a break; statement to exit the loop every and some methods work differently.

Here’s a description of what every method is from Mozilla Documentation.

The every() method is an iterative method. It calls a provided callbackFn function once for each element in an array, until the callbackFn returns a falsy value. If such an element is found, every() immediately returns false and stops iterating through the array. Otherwise, if callbackFn returns a truthy value for all elements, every() returns true.

From MDN

every() method will return true only when all the items in the array are truthy. In particular, for an empty array, every method will return true.

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
fruits.every(fruit => {
  console.log(fruit);
  return fruit !== "🥑";
})

To break/exit the iteration we are returning the negated condition to make it false when we see an avocado. So, it prints all fruits till avocado.

.some()

The some() method is an iterative method. It calls a provided callbackFn function once for each element in an array, until the callbackFn returns a truthy value. If such an element is found, some() immediately returns true and stops iterating through the array. Otherwise, if callbackFn returns a falsy value for all elements, some() returns false.

From MDN

In contrast to every method, some method will exit the iteration when it sees a truthy value.

let fruits = ["🍎", "🍌", "🍊", "🥑", "🍉"];
let fruitFound = false;
fruits.some(fruit => {
  console.log(fruit);
  return fruit === "🥑";
})

The iteration continues until it finds an avocado. If the fruit is found, then the loop will be exited without executing the other items in the array.

The .some method is the closest thing that resembles exiting a .forEach loop in JavaScript.

References

Disqus Comments Loading...
Share
Published by
Karthik Chintala

Recent Posts

2 Good Tools To Test gRPC Server Applications

In this post, we’ll see how to test gRPC Server applications using different clients. And… Read More

2 years ago

Exploring gRPC project in ASP.NET Core

In this post, we'll create a new gRPC project in ASP.NET Core and see what's… Read More

2 years ago

Run dotnet core projects without opening visual studio

In this blog post, we’ll see how to run dotnet core projects without opening visual… Read More

2 years ago

Programmatically evaluating policies in ASP.NET Core

Programmatically evaluating policies is useful when we want to provide access or hide some data… Read More

2 years ago

Multiple authorization handlers for the same requirement in ASP.NET Core

We saw how we could set up policy-based authorization in our previous article. In this… Read More

2 years ago

Policy-Based Authorization in ASP.NET Core

What is policy-based authorization and how to set up policy-based authorization with handlers and policies… Read More

2 years ago

This website uses cookies.