Can u stop a forEach function ?
A simple question: Suppose you call a forEach function. Do u think anyhow you can stop the execution in midway?
let sampleArr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]sampleArr.forEach((entry) => {
console.log(entry) // do anything
if (entry === 4) {
// i want to stop this forEach execution after it reaches 4
}
})
Well if your answer is NO and you know the alternatives to do this, go ahead you can skip this article. For the rest of you follow along.
The simplest thing u can try is either call return in the if block or try adding a break statement.
But that will have no effect.
// return will simply stop the further execution of the current callback but the forEach will go on.
// break won’t do anything, because the break call is not technically in the loop.
So what options do i have:
- For loop #smiley:
u don't need anything here - Use Lodash:
If in Lodash forEach function u do
```return false```
It stops the forEach loop execution
while simply doing a return stops the current callback execution - throw an exception and wrap with a try-catch.
- Use every or some iteration methods.
Here’s a repl link for testing it out
https://repl.it/@sanchitbansal10/stop-forEach-execution
Hope it helps. Thanks for reading