I'm asking in terms of a loop, obviously break
is important in switch
statements. Whether or not switch
statements themselves are code smells is a separate issue.
So consider the following use cases for iterating a data structure:
- You want to do something to the entire structure (no break needed)
- You want to do something to part of a data structure.
- You want to find something(s) in the data structure (which may or may not involve iterating the entire structure)
The above list seems more-or-less exhaustive to me, maybe I'm missing something there.
Case 1 can be thrown right out, we can use map
/forEach
. Case 2 sounds like filter
or reduce
would work. For case 3, needing to iterate the data structure to find something seems plain wrong, either the data structure itself should provide a relevant method or you are likely using the wrong data structure.
While not every javascript data structure (or implementation) has those methods it's trivially simple to write the relevant functions for pretty much any javascript data structure.
I saw this when researching but it is explicitly in the context of C/C++. I could understand how it would be more-or-less a necessity in C, but my understanding is that C++ has lambdas and many data structures are generally objects (e.g. std::vector
, std::map
), so I'm not sure I understand why the answers are all so universally in favor of break
there, but I don't feel I know C++ well enough to even begin to comment.
I also realize that for some corner-case exceedingly large data structure the cost of iterating the entire structure may be unacceptably high, but I doubt those are very common when working even in node.js. Certainly it's the kind of thing you'd want to profile.
So I just don't see a use-case for break
in today's javascript. Am I missing something here?
[0...5]
is equivalent to[0,1,2,3,4]
. So repeating any action n times is essentially the same as callingforEach
on an array of n elements.break
andfilter
are interchangeable. In one case, you iterate until you encounter the first element that satisfies a predicate, in the second, you loop over all elements that satisfy a predicate. As in “cook me food on all days until Friday” versus “cook me food on all days that are work-days”.if(iterations > max) break;
to ensure it doesn't hang the system, not just game loops. Such as interpreters which have a maximum recursion level, or linters which have a maximum number of errors they'll warn about before shutting up, etc. Kilian's original comment was basically correct.map
,foreach
andfilter
don't help when the problem is "operate on all elements up to the first one that satisfies some condition." I'd go so far as to argue that usingreduce
for that case instead of a straight loop with abreak
is a code smell because it's less readable.