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!