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

Allen Wirfs-Brock allen at wirfs-brock.com
Sat Jun 8 23:13:08 PDT 2013


On Jun 8, 2013, at 10:34 PM, Axel Rauschmayer wrote:

> I can’t find the rationale as to why that isn’t allowed. Is it because iterators can’t be recognized as safely as iterables?

Both Iterators and Iterables may be ordinary objects.  There has to be some way for for-of to recognize one or the other. The way that an Iterable is recognized is by the presence of an @@iterator method. An Iterator is only required to have a "next" method. Checking for the unique symbol @@iterator seems much less likely to produce false positives then checking for "next".

The other way to look at it is that for-of is designed to iterate over the elements of a collection (an Iterable) so that is what it checks for.  An Iterator is jus part of the mechanism for implementing for-of iteration.

> 
> If we did enable for-of (and Array.from) for iterators, we would get two advantages:
> 
> - Generators would not need to have a method @@iterator.

why is this a big deal?  It is provided by the standard generator prototype that all generators inherit from. 

> - Many functions actually return iterators, but have to turn them into iterables (by adding a method @@iterator that returns `this`) to work with for-of.

As a rule of thumb, if an Iterator is produced by a @@iterator method it probably doesn't need to also be an Iterable.  If an Iterator is produced by any other method it probably should be an Iterable.

It seems easy enough to define a class that has a @@iterator() {return this} method and then to subclass class it for you specific Iterables.

Allen




More information about the es-discuss mailing list