JavaScript Runtime Semantics

Iterables, Iterators & Generators

The iterable protocol lets objects define how they are consumed by for...of, spread, destructuring, and many collection APIs. Generators provide a compact way to produce custom iterators.
  • An iterable has Symbol.iterator
  • An iterator has next()
  • Generators create iterators with yield
  • Iteration can be lazy
  • for...of and for...in are different
Iteration protocol terms
TermShapeUsed by
IterableHas Symbol.iteratorfor...of, spread, destructuring
IteratorHas next()Protocol consumer
Generatorfunction* with yieldLazy iterator authoring
Async iterableHas Symbol.asyncIteratorfor await...of
Lazy range
function* range(start, end) {
  for (let i = start; i <= end; i++) {
    yield i
  }
}

console.log([...range(1, 3)]) // [1, 2, 3]
The generator yields values one at a time; spreading consumes it into an array.
Sources
  • MDN JavaScript Guide and ReferenceIterators and generators
  • ECMAScript Language SpecificationIterator objects
  • The Modern JavaScript TutorialGenerators and iteration