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

Allen Wirfs-Brock allen at
Sun Jun 9 23:07:47 PDT 2013

On Jun 9, 2013, at 7:17 PM, Brendan Eich wrote:

> 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:

That's what is essentially currently spec'ed.  All the built-in iterators are specified in that way and for-or essentially expects that behavior.  By reading of this thread is that people were looking for ways to avoid having to explicitly define a method like
  [iteratorSymbol] () {return this}
for those situations.

> 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
> true
> (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?

I won't want to suppress any exceptions.  If next wasn't there you would get an exeption when for-of tried to invoke it.

> That seems worse than the Python way. We don't want the case where there *is* an @@iterator to suppress missing/non-callable 'next'.

No supression, the semantics of e in
   for (let x of e)
is would essentially be
   let iter = Reflect.has(e,@@iterator)? e[@@iterator]() : e;

>> in that case we could say:
>>    function combine(bowls) {
>>        let iterator = bowls[iteratorSymbol]();
>>        let {value: firstBowl, done} =;
>>        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 ticket on this?

I really just need us to reach consensus on what we want to have.

I think what is currently spec'ed (for-of requires an @@iterator) is fine.  But I also think falling back to just using the supplied value as the iterator would be ok.

> /be

More information about the es-discuss mailing list