Non-obvious behaviors in Javascript foreach() loop
I want to show two inconspicuous-looking behaviors in Javascript foreach() loop that could confuse you while using it.
How to stop foreach loop in Javascript?
At first look pretty simple, inconspicuous-looking question, isn’t it? But it is Javascript… so any question could be tricky 😏
Let’s look at the sample code below (you can edit and run it)
It prints every number from array but return keyword is ineffective here. As is turns out, this is correct behavior according to documentation:
There is no way to stop or break a
forEach()loop other than by throwing an exception.
So, we have only one way to stop this loop:
Now the loop is successfully stopped but… isn’t it looks like using cannon to kill a fly? So if you have to break loop you should consider to use e.g for loop instead foreach
Async function in foreach loop - will it work?
The second thing in foreach loop that could be misleading is:
foreach()expects a synchronous function - it does not wait for promises
Check this code:
As you can see, async function is not awaited.
Maybe for someone this two topics are obvious, but for me both of presented behaviors were unexpected (until today 😉).