Incompatibility between generators and arrays in the Iterator protocol

Tim Jansen ml at
Tue Jun 30 18:13:15 UTC 2015


I am working on a collections library that supports the Iterable/Iterator
protocol, but I ran into a stumbling block: the iterator protocol seems to
work differently for arrays and generator functions. Array iterators set
'done' to true *after* the last element, but function generators set 'done'
to true *on* the last element.

Is this incompatibility intentional, or or just an implementation issue in
the browsers (tested on FF38 and Chrome 43)? I wasn't able to find any
information on this. The ES6 draft from April '15 doesn't define when
exactly 'done' is set.

Code example:

var a = ['a', 'b'];

var itA = a[Symbol.iterator];;   // {value: 'a', done: false};   // {value: 'b', done: false} !!;   // {value: undefined, done: true}

function* b() {

  yield 'a';

  return 'b';


var itB = a[Symbol.iterator];;   // {value: 'a', done: false};   // {value: 'b', done: true} !!!;   // {value: undefined, done: true}

The difference is in the second invocation of next(), which returns true
for generator functions. That protocol makes it impossible for me to
support both generator functions and array iterators with the same
implementation - at least if I want to support 'undefined' as a valid value
in collections. I wouldn't be able to differentiate between an empty list
([]) and a list containing undefined ([undefined]).


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list