forEach() break out of loop
1 | array = [1, 2, 3, 4]; |
What happens?
From the official MDN docs:
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Explanation:
forEach will execute the callback function to each iterable, it doesn’t care you exit once or not.
The same thing happens to “continue” and “break”, they do not work as well.
Solution:
Just use normal loop:
for (let i = …; i < … ; i++){
}