How to break out of forEach in JavaScript

Updated onbyAlan Morel
How to break out of forEach in JavaScript

JavaScript added the forEach array method as part of ES5.

This function allows you to call a function on every single element in an array, essentially acting like a for loop.

However, because it is not a for loop but instead a function being run, you cannot use the break keyword with forEach.

In this post, we'll explore how you can mimic breaking out of a forEach method.

Break out of a forEach

Let's first look an example forEach loop by calling it on an array of numbers.

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]; numbers.forEach(number => { console.log(number); });

Inside our forEach method, we are simply logging the value of the current element.

BASH
1 2 3 4 5

Let's say you wanted to stop after the third element.

As mentioned before, using break will not work with forEach.

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]; numbers.forEach(number => { console.log(number); if (number === 3) { break; // won't work } });

Instead, you can try using a boolean as a flag. You can enable it whenever you want to break out of the loop.

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]; let flag = false; numbers.forEach(number => { if (flag) { return; } if (number === 4) { flag = true; return; } console.log(number); });
BASH
1 2 3

This functions correctly, but it is not very efficient because it is checking the flag every time.

However, this is about as good as we can get with a forEach loop, since as mentioned before, a method has to be called on every single element, no matter what.

In general, if you must break out of a loop, you should avoid using forEach and instead use a regular loop, however, it is still possible to simulate using break as shown above.

Conclusion

In this post, we've covered how to break out of a forEach loop by using a boolean flag.

It's not ideal but it's the best way to simulate a break keyword inside a forEach function.

Hopefully it helps you out and thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.