DEV Community

Discussion on: JavaScript loop querySelectorAll results

Collapse
 
grayedfox profile image
GrayedFox • Edited

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!

Collapse
 
dailydevtips1 profile image
Chris Bongers

Ah yes, would it not stop if you would in that case put a return inside the forEach?

Collapse
 
grayedfox profile image
GrayedFox

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}`)})
Enter fullscreen mode Exit fullscreen mode

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 :) 🙇

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

Ah good to know indeed!
In most cases, I always want to attach listeners to all, but indeed strong argument!