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 Solid
Managing PHP Dependencies with Composer
Create an RSS Reader in Node
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a MySQL Server using Docker
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Getting Started with Moment.js
Setting Up a Local Web Server using Node.js
