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
- Throwing an error in
.forEach
loop - 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
Karthik is a passionate Full Stack developer working primarily on .NET Core, microservices, distributed systems, VUE and JavaScript. He also loves NBA basketball so you might find some NBA examples in his posts and he owns this blog.