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

Claude Pache claude.pache at
Wed Jun 12 14:27:24 PDT 2013

Le 12 juin 2013 à 20:46, Andreas Rossberg <rossberg at> a écrit :

> On 12 June 2013 19:51, Brendan Eich <brendan at> wrote:
>> The @iterator part of the iteration protocol is not about coercion or types
>> at all. It is a "pattern" for getting or creating a usable iterator from an
>> object.
> You are entitled to call it what you think is best, of course, but in
> the current state of affairs, implicit coercion is the only thing
> @iterator actually gives you. Simple test: if you removed it from the
> picture (in favour of for-of just accepting iterators) that would be
> the only thing you'd lose.

Given that:
* an iterator can be used in only one for/of loop;
* an iterable (by which I mean primarily, an iterable non-iterator) can typically be reused in other for/of loops, including nested ones;
when I write `for (item of mySet)`, I consider that what I've written on the RHS of the 'of' keyword is definitely a (non-iterator) *iterable*—since I can reuse it two lines below—, and not something coerced to an *iterator*—that I couldn't reuse.

Therefore, I think that "For/of coerces its argument to an iterator" is a wrong mental model, and "For/of accepts either a reusable iterable or a disposable iterator" is a better one. And the implicit invocation of `@@iterator` is better thought as Get-the-snark-I-need-for-doing-my-work, than as Coerce-to-a-disposable-object. (And the fact that iterators are also non-reusable iterables is an implementation detail that don't disturb my mental model, because I don't care, thanks to generators.) 


More information about the es-discuss mailing list