DEV Community

Cover image for Why can't you break out of the forEach loop?

Why can't you break out of the forEach loop?

mayankav on September 29, 2021

This is one of the many things I keep forgetting every now and then. Other things like taking out clothes from the washing machine, watering my pla...
Collapse
ย 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข โ€ข Edited

You can throw an exception. Not the prettiest solution, but it works...

const BreakException = {}
try {
  [1, 2, 3].forEach(function(el) {
    console.log(el)
    if (el === 2) throw BreakException
  });
} catch (e) {
  if (e !== BreakException) throw e
}
Enter fullscreen mode Exit fullscreen mode

Another way is to just use some and return a truthy from your function if you want to break out:

[1, 2, 3].every(function(el) {
   console.log(el)
   if (el===2) return true
})
Enter fullscreen mode Exit fullscreen mode
Collapse
ย 
lionelrowe profile image
lionel-rowe โ€ข

Why use an unreadable, hacky solution when for... of exists?

Collapse
ย 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข

Many ways to skin a cat, couldn't be bothered to list them all

Thread Thread
ย 
lionelrowe profile image
lionel-rowe โ€ข

What I'm saying is, if you care about code quality, why not use the best tool for the job?

Thread Thread
ย 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข โ€ข Edited

I care about code. I care about, and am interested in the many permutations that can achieve the same result - including all the weird and wonderful ways. To me, that's the beauty of code, and is why I love it. Correctness, readability, and quality are purely subjective. I personally cannot think of anything worse than blindly following the dogmatic methodologies promoted as the best, or right way to do things - without playing and enjoying exploring alternatives.

Writing code, from my perspective, is more like art crossed with science than engineering. It's a very personal thing - like writing a novel, or poetry, or painting a picture. There can very definitely be beauty in it.

This approach does inevitably clash with others who follow a more traditional software engineering route, but it has served me well over the 38 years I've been writing code.

Thread Thread
ย 
lionelrowe profile image
lionel-rowe โ€ข

I sympathize with that approach for sure, but I see it as similar to writing prose, which is certainly a creative endeavor. Sure, you could write an essay caPitALiZIng RAndOM leTtErs or spelฤฑng uerds uฤฑth ior oun ฤฑnventฤฑd orthogr'fy, but who would want to read it, much less be your co-writer on it? There are conventions for a reason, and you should have an even better reason if you want to break them. That doesn't mean for a second that you can never break them โ€” it just means that, for example, you should typically avoid adding complexity where you don't gain something (performance, flexibility, etc) of at least equal value in return.

Collapse
ย 
shuckster profile image
Conan โ€ข

Nice explanation as to why break wonโ€™t work by writing your own version of forEach.

I know you linked to some alternatives already and this is probably familiar, but hereโ€™s an example I popped together using some / every.

Collapse
ย 
mayankav profile image
mayankav โ€ข

@shuckster I like what you did there on zansh.in

Collapse
ย 
przemek profile image
Przemyslaw Michalak โ€ข โ€ข Edited

You can't break from forEach because that's the purpose of forEach loop. In JS you have reduce, map, while, do while, for, filter and god knows how many other types of loops. The reason for forEach to exist is to NOT allow you to break from it! It's like complaining that the sit belt in the car have a functionality of saving your life in the accident, well... that's the purpose, not a flaw.

Collapse
ย 
mayankav profile image
mayankav โ€ข โ€ข Edited

Hey man! appreciate the analogy. There can indeed be many more reasons why you'd go with a forEach loop (keeping variables scoped, clean abstraction etc..). Tbh, I dont really know the motivation(s) behind the creation of forEach in the first place but that hardly matters. This is just me pointing out a simple mistake that most of us make. I do this over and over even when I know the stuff.

Collapse
ย 
ben profile image
Ben Halpern โ€ข

Ha, great post

Collapse
ย 
haiderali2162 profile image
haiderali2162 โ€ข

Good job๐Ÿ’—๐Ÿ’—๐Ÿ’—๐Ÿ’—๐Ÿ’—
Thank you....

Collapse
ย 
kuya1284 profile image
kuya1284 โ€ข

I think defining your own custom forEach loop is redundant. You can use what's already available, like using Array.some().

If you need to simulate "continue" in a forEach loop, use "return".

Collapse
ย 
mdqayyumshareef profile image
Qayyum Shareef โ€ข

I think we can use 'return' to exit for each loop.