I would note that while forEach is versatile and easy on the eyes, the other loops have the advantage of allowing an early break/continue/exit.
forEach loops will iterate over every single element even if you've done what you need to, so if you want to do something greedily (like find the first node that matches some condition), you're better off using a traditional for loop.
Aside from that I also tend to lean towards forEach!
Not according to this code I just threw into my browser console:
[0, 1, 2, 3, 4].forEach(e => { if (e == 3) { return; } console.log(`${e}`)})
The above logs 0, 1, 2, undefined, 4. Also the MDN docs state in a big yellow warning box "There is no way to stop a forEach() loop other than by throwing an exception": developer.mozilla.org/en-US/docs/W...
They also recommend using for...of or for...in if breaking out early is desired :) 🙇
Thanks for the post!
I would note that while forEach is versatile and easy on the eyes, the other loops have the advantage of allowing an early break/continue/exit.
forEach loops will iterate over every single element even if you've done what you need to, so if you want to do something greedily (like find the first node that matches some condition), you're better off using a traditional for loop.
Aside from that I also tend to lean towards forEach!
Ah yes, would it not stop if you would in that case put a return inside the forEach?
Not according to this code I just threw into my browser console:
The above logs 0, 1, 2, undefined, 4. Also the MDN docs state in a big yellow warning box "There is no way to stop a forEach() loop other than by throwing an exception": developer.mozilla.org/en-US/docs/W...
They also recommend using for...of or for...in if breaking out early is desired :) 🙇
Ah good to know indeed!
In most cases, I always want to attach listeners to all, but indeed strong argument!