Forwarding `return()` in generators

Bergi a.d.bergi at
Tue Mar 24 20:21:36 UTC 2015

Axel Rauschmayer wrote:

> AFAICT, `return()` throwing an exception (versus performing a `return`) is necessary

It's not necessary, it just might be a bit more complicated:

     function* take(n, iterable) {
         let iterator = iterable[Symbol.iterator]();
         n = +n; // make sure it's a number, so that n>0 does never throw
         try {
             while (n > 0) {
                 let item =;
                 if (item.done) {
                     return item.value;
                 yield item.value;
         } catch (e) {
         } finally {

(I assume calling `throw` or `return` on a finished iterator is simply 
ignored, I'll have to check this back with the spec).
The above code also has the additional nice property that it call 
`.return()` on the iterator when `n` values have been taken out of it.


More information about the es-discuss mailing list