Throwing StopIteration in array extras to stop the iteration

Tab Atkins Jr. jackalmage at
Tue Mar 5 10:00:56 PST 2013

On Tue, Mar 5, 2013 at 9:38 AM, Kevin Gadd <kevin.gadd at> wrote:
> Maybe I'm overlooking some past discussion on this, but if you want to
> be able to generally terminate iteration in constructs like
> Array.forEach (this seems like a pretty real world use-case), why not
> introduce an additional argument to the forEach/etc callbacks, for an
> 'iteration token'?
> I.e. if forEach currently passes 'item, index, array' to the callback,
> it can pass 'item, index, array, token'. token can be an object, such
> that:
> token.stopIteration(); // probably a better name for this
> terminates iteration.
> This has some upsides:
> You can mechanically detect a conforming implementation by looking for
> the token object via arguments[3]
> There's no risk of code written for a conforming implementation
> causing weird side effects (like an uncaught StopIteration) in a
> non-conforming iteration; it'll fail meaningfully
> The token is conceptually easy to understand and the implementation cost is low

Additional upside: we can canonically call the argument "halt", thus
finally completing Brendan's name in forEach's signature:
forEach(Element, Index, Collection, Halt).  ^_^


More information about the es-discuss mailing list