Throwing StopIteration in array extras to stop the iteration

David Bruant bruant.d at
Tue Mar 5 03:42:08 PST 2013

Le 05/03/2013 00:31, Jason Orendorff a écrit :
> On Sun, Mar 3, 2013 at 12:45 PM, David Bruant <bruant.d at 
> <mailto:bruant.d at>> wrote:
>             [2, 8, 7].forEach(function(e){
>                 if(e === 8)
>                     throw StopIteration;
> This would be taking a piece of one low-level protocol, and using it 
> for a sorta-kinda related thing that actually, on closer inspection, 
> has nothing to do with that protocol. Array.prototype.forEach doesn't 
> even use iterators.
I could not agree more. I'm aiming at a least-worst type of solution, 
rather than something good.

Currently, if one wants to do stop an iteration early, he/she has to be 
done one of the following way:
         [2, 8, 7].forEach(function(e){
                 if(e === 8)
                     throw "whatever";
         // do nothing, I just want to catch the error in case the iteration
         // stopped before traversing all elements

2) (ab)using some and every

Downsides to each solution
1) If you care about good use of protocols, I hope you'll agree that the 
try/catch protocol is severely abused
Brendan wrote:
> Are the some and every names confusing? Would any and all be better?
The problem is that there are 2 of them and stopping the iteration is 
returning true in one case, false in the other. People are smart, 
memorize what they need to know. I know I spend more time reading 
some/every code than normal just to be sure of what true and false 
means. It might be because I'm not a native English speaker that I have 
to extra-think on every/some, but that's not an excuse anyway.

"return true/false" to stop an iteration early does not make very 
readable code.
Recently, I was helping a friend with some code he needed help to fix. 
Code that had been written in team. He asked me "but how do you know 
where the problem is without having to read all the code?". To which I 
answered "Do you see the 'queue.persist()'? I know it persists the queue 
and does nothing else, I don't need to read that code".
I wish whenever I want to stop an iteration early, I didn't have to flip 
a coin to choose some and every and the corresponding true/false 
semantics but had something as readable as queue.persist to say what I mean.

I thought I was doing a clever "language hack" by reusing 'throw 
StopIteration' exactly in a context where it's not supposed to have a 
Apparently I was not.

I'm happy of the outcome of the thread if .findIndex is introduced, but 
I can't help wondering whether a new method is going to be introduced 
every single time someone brings up a pattern that would make good use 
of stopping an interation early.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list