break-from-foreach-in-javascript

How to Break from forEach in JavaScript?

There is no direct way to break from the forEach() function, however, there are some workarounds.

Introduction

In JavaScript, forEach() is a FUNCTION that loops over an array of elements. It takes a callback as a parameter and applies it to every element in the array.

I know that you landed on this page to know the direct way to break from forEach(), but I’m sorry to tell you that you can’t. As MDN:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

MDN

Having said that, you shouldn’t use forEach() if you know previously that you might need to break from the loop. Instead, you should use for...of, that’s the perfect solution.

However, for just the sake of learning, let’s introduce some workarounds.

First of all, let’s consider the following example as a basis:

Consider the case, you want to break if the element was 3.

Using for…of Instead

As I said, that’s the recommended solution as you can break from the loop easily using the break keyword.

Using every() or some() Instead

In JavaScript, every() and some() are two functions like forEach(), the difference is that:

  • every(): Returns true if every callback returns true.
  • some(): Returns true if one callback at least returns true.

đź’Ś Enjoying this post? Subscribe to get more practical dev tips right in your inbox.

Fortunately, we can use these facts to break the loop as follows:

  • every(): You should return false at the element you want to break out.
  • some(): You should return true at the element you want to break out.

Firstly, let’s use every():

Secondly, let’s use some():

Using a Variable Helper

In this workaround, you retain using the forEach() function. In addition, you use a variable that controls the flow.

Conclusion

In this article, we knew that there is no direct way to break from the forEach() function.

Then, we knew that it is preferable to use for...of instead of looping over an array of elements.

Finally, we introduced some workarounds that you can use to break from the forEach() function, like using other functions like every() or some(), or by using a variable helper that controls the flow.

Think about it

If you enjoyed this article, I’d truly appreciate it if you could share it—it really motivates me to keep creating more helpful content!

If you’re interested in exploring more, check out these articles.

Thanks for sticking with me until the end—I hope you found this article valuable and enjoyable!

Want more dev insights like this? Subscribe to get practical tips, tutorials, and tech deep dives delivered to your inbox. No spam, unsubscribe anytime.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top