We recommend using for/of loops to iterate through an array unless you have a good reason not to. However, if you find yourself stuck with a forEach() that needs to stop after a certain point and refactoring to use for/of is not an option, here's 4 workarounds:
1. Use every() instead of forEach()
The every() function behaves exactly like forEach() , except it stops iterating through the array whenever the callback function returns a falsy value.
With every() , return false is equivalent to a break , and return true is equivalent to a continue .
Another alternative is to use the find() function, which is similar but just flips the boolean values. With find() , return true is equivalent to break , and return false is equivalent to continue .
2. Filter Out The Values You Want to Skip
Instead of thinking about how to break out of a forEach() , try thinking about how to filter out all the values you don't want forEach() to iterate over. This approach is more in line with functional programming principles.
The findIndex() function takes a callback and returns the first index of the array whose value the callback returns truthy for. Then the slice() function copies part of the array.
3. Use a shouldSkip Local Variable
If you can't use every() or slice() , you can check a shouldSkip flag at the start of your forEach() callback. If you set shouldSkip to true , the forEach() callback returns immediately.
This approach is clunky and inelegant, but it works with minimum mental overhead. You can use this approach if the previous approaches seem too clever.
4. Modify the array length
The forEach() function respects changes to the array's length property. So you can force forEach() to break out of the loop early by overwriting the array's length property as shown below.
1. `return` statement Doesn’t stop the loop
the reason for this behaviour is that we are passing a callback function in our “foreach” function, which behaves like a normal function and is appliead to each element no matter if we “return” from one.
2. `break` statement Don’t work
do you think “foreach” loop break when equals to 3 ?
The above code will throw an exception
This is because , technically the break not inside a loop.
3.`Continue` statement would not work as well
Do you think this code only print “1, 2, 4 ” ?
No, You are wrong. You would end with the following exception:
Yes! The continue statement is not executing inside a loop, similar to the break incident mentioned above.
Remember this : YOU CAN’T BREAK A FOREACH IN A GOOD WAY ! (but there are good alternatives …).
With a for loop, use “break”:
The every() method will test all elements of an array (all element must pass the test). It is a good alternative to replace “forEach” for breaking an array:
The some() method will test all elements of an array (only one element must pass the test). It is also good alternative to replace “forEach” for breaking an array:
Как завершить цикл foreach js
Stopping a forEach() loop seems almost like an impossible task but here are a few tricks by which we might do it.
Sample example using forEach():
Tricks to stop forEach() loop:
Method 1:The following method demonstrates using a try-catch block. The following code demonstrates surrounding the thing with a try-catch block and throwing an exception when forEach loop break.
Table of contents
Let’s look at the following code snippet.
You would expect the code to stop executing after it finds the name “Steph”; however, it throws an Unsyntactic break error.
As in most things in programming, there is, of course, a workaround. We can throw and catch an exception while iterating our array. Let’s take a look at how we could achieve this.
As you can see here, we wrapped our forEach statement in a try catch block. Where we would typically do a break, we perform a “throw ‘Break’“
We then jump down to our catch and check what our error is. If it’s anything other than “Break“, we throw it up the error chain. Otherwise, we continue with our code execution.
Although this solution works, it’s not very clean. Let’s take a look at a few better alternatives.
Alternative #1: for…of loop (Preferred)
The for…of loop would be the preferred solution to this problem. It provides clean easy to read syntax and also lets us use break once again.
Another added benefit of using the for…of loop is the ability to perform await operations within it. We would not be able to use the await syntax within a forEach loop.
Alternative #2: every
We can also use the “every” array prototype. Let’s take a look at that code snippet.
The every prototype will test each element against our function and expect a boolean return. When a value is returned false, the loop will be broken. In this case, we inverse our name test and return false when the name is equal to “Steph”, the loop breaks, and we continue our code.
Alternative #3: some
Very similar to the every prototype, we could also use the “some” array prototype. The some prototype is almost identical to the every prototype. The only difference is that a true return will break the loop. Let’s take a look at the code.
You can see that the function returns true when it reaches the “Steph” name and breaks the loop. Whether you choose some or every is entirely dependent on what you believe to be the most readable.