How do you stop a forEach loop in JavaScript?

NicolasBrondinBernard

Author
@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

nicolasbrondinbernard_A_knot_made_with_a_rope._Background_100_w_c578ca08-cfb7-4a54-8c92-b1aa011bb6bc.png

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 true to keep the loop running.


Finished reading this article?
Our newsletter

No spam. Only free content, news, and ever more resources to level up your skills!

Join +1500 developers

Comments (0)

to leave a comment

No comments yet