How do you stop a forEach loop in JavaScript?
NicolasBrondinBernard
Find out how to do it by working around the problem using the `some()` method

Article published on 13/08/2024, last updated on 10/08/2026
If you're looking for an equivalent to the break command used in classic for() loops, but for forEach() loops…
To put it briefly, it doesn't exist. But wait, don't leave just yet!
There is actually a solution that works very well, and that allows you to:
- Keep the functional syntax of
forEach() - Keep the optimization of
break

The solution
Let's take an example of a very simple forEach() loop to understand how to achieve our result:
const data = [1, 2, 3, 4, 5, 6];
data.forEach((item, index, arr)=>{
if(item >= 3) {
// do something
// stop
}
});
The forEach() loop will only stop once the ENTIRE list has been traversed.
But to make our code more efficient, all we need to do is replace forEach() with some(), like this:
const data = [1, 2, 3, 4, 5, 6];
data.some((item, index, arr)=>{
if(item >= 3) {
// do something
return true;
}
});
The some() method allows you to check that at least one element of the provided list meets the expected conditions. As long as we return false or void, the loop continues, but it stops as soon as it receives the value true!
Here we're slightly diverting its classic usage, in order to optimize the number of loop iterations performed.
Find the documentation for the some() method right here
Alternative
If your code is more inclined to return the value false to stop the loop, you can simply replace the some method with every.
Be careful though, you'll need to remember to always return
trueto keep the loop running.
No spam. Only free content, news, and ever more resources to level up your skills!
Join +1500 developers
No comments yet