How to break out of forEach in JavaScript
Table of Contents
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.
JAVASCRIPTconst 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.
BASH1
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
.
JAVASCRIPTconst 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.
JAVASCRIPTconst numbers = [1, 2, 3, 4, 5];
let flag = false;
numbers.forEach(number => {
if (flag) {
return;
}
if (number === 4) {
flag = true;
return;
}
console.log(number);
});
BASH1
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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- Getting Started with Deno
- How to deploy a Node app using Docker
- Getting Started with Sass
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications