Why can’t for-of be applied to iterators?

Brendan Eich brendan at mozilla.com
Sun Jun 9 19:17:22 PDT 2013

Allen Wirfs-Brock wrote:
> Currently the spec. days that if it is not an Iterable the for-of loop 
> doesn't run (although some of the details in the For In/Of Expression 
> Evaluation looks a little bogus).  It would be easy enough to to spec. 
> it such that if the value is not an Iterable (does not have an 
> @@iterator property) then it just assumes that it must already be an 
> Iterator.

Of we could do what has been proposed since ES4 days, and (after Python) 
make @@iterator for an iterator return that self-same iterator:

js> a = [1,2,3]
[1, 2, 3]
js> a.iterator
function iterator() {
     [native code]
js> it = a.iterator()
js> it.iterator
function iterator() {
     [native code]
js> it.iterator() === it

(SpiderMonkey latest, no unique iteratorSymbol yet.)

Just assuming an iterator if there is no @@iterator means trying .next() 
with exception suppression when there is no 'next' or its value is not a 
function, right? That seems worse than the Python way. We don't want the 
case where there *is* an @@iterator to suppress missing/non-callable 'next'.

> in that case we could say:
>     function combine(bowls) {
>         let iterator = bowls[iteratorSymbol]();
>         let {value: firstBowl, done} = iterator.next();
>         if (done)
>             return;  // no bowls at all
>          for (let bowl of iterator)
>             dumpInto(bowl, firstBowl);
>     }

This is as good as it gets, btw -- Jason's Python didn't handle the "no 
bowls at all" case.

Do you want a bugs.ecmascript.org ticket on this?


More information about the es-discuss mailing list