Throwing StopIteration in array extras to stop the iteration

David Bruant bruant.d at gmail.com
Tue Mar 5 09:56:02 PST 2013


Le 05/03/2013 18:32, Jason Orendorff a écrit :
> On Tue, Mar 5, 2013 at 5:42 AM, David Bruant <bruant.d at gmail.com 
> <mailto:bruant.d at gmail.com>> wrote:
>
>     Currently, if one wants to do stop an iteration early, he/she has
>     to be done one of the following way:
>     1)
>         try{
>
>             [2, 8, 7].forEach(function(e){
>                     if(e === 8)
>                         throw "whatever";
>                     console.log(e)
>             }
>         }
>         catch(e){
>             // do nothing, I just want to catch the error in case the
>     iteration
>             // stopped before traversing all elements
>         }
>
>
> Well... here's what I would do.
>
>     for (var e of [2, 8, 7]) {
>         if (e === 8)
>             break;   // exiting JS loops since 1994
>         console.log(e);
>     }
>
> Why not use statements for your procedural code?
I love the idea of for-of, and that's probably what I'll use in the 
future indeed (for-of isn't available since 1994 ;-) )

I've realized that in a recent Node.js experience I had made no 
off-by-one errors and I consider the extensive use of forEach&friends to 
be the reason for that.
The iterator protocol and for-of loops by extension provide the same 
guarantee that forEach (with the possibility to break) so I guess I'll 
use that whenever possible.

Thanks,

David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130305/5f1ca2c6/attachment.html>


More information about the es-discuss mailing list