DEV Community

Cover image for Why you can't break a forEach loop | ByteSize JS

Why you can't break a forEach loop | ByteSize JS

Jared on March 31, 2020

I recently had a coding interview that involved evaluating one schema against another. The details of it aren't that important, but one thing that ...
Collapse
 
folke profile image
Folke Lemaitre β€’ β€’ Edited

You can use .every() instead and return false whenever you want to break. Return true to keep going

Collapse
 
codenutt profile image
Jared β€’

Interesting! Thank you for your insight. I haven't used every much. Very handy!

Collapse
 
folke profile image
Folke Lemaitre β€’

.some() is probably even better in most cases. Just return true whenever you need to break. No need to return anything when you want to keep going :)

Thread Thread
 
codenutt profile image
Jared β€’

Sweet! May have to do a deep dive article into all the various loop types.

Collapse
 
monfernape profile image
Usman Khalil β€’

This is so helpful

Collapse
 
codenutt profile image
Jared β€’

Thanks! Any other topics you'd like me to tackle?

Collapse
 
kenbellows profile image
Ken Bellows β€’ β€’ Edited

Awesome article! Minor nitpick though: Array.prototype.forEach() and its siblings map, filter, reduce, reduceRight, some, and every were all actually introduced back in 2009 with ES5!

I bring this up not for know-it-all points, but because it's important for browser compatibility. Most of these methods are available in browser versions going back 10+ years, which is super important and helpful if, like me, you work in an environment where you still need to maintain support for those browsers 😭

Collapse
 
codenutt profile image
Jared β€’

Thank you for the correction! I'm the only one who edits these things, so I appreciate any and all feedback. I'll update it to reflect accurate info!

I feel you though, I have to support old browser's too

Collapse
 
gnunesleonardo profile image
Leonardo Gomes Nunes β€’

I always remember that forEach() loop can't be break but i never know why, until now haha. Great article, thanks!

Collapse
 
codenutt profile image
Jared β€’

Thanks!

Collapse
 
sunny_chan2012 profile image
Sunny Chan β€’

But why they keep all these different versions of doing the same things? That is, forEach(), every() and some().

Collapse
 
szalonna profile image
Joe β€’

I mean, you can if you really want: just throw sg from the callback.