liveBook · Manning

Iterator

As explained in Functional Programming in JavaScript

An iterator is an object or abstraction that provides successive values from a sequence or data source through a traversal protocol.

An iterator is a small object that remembers traversal state and supplies the next value only when asked. This supports lazy data generation: callers can consume a few values without creating an entire collection first. section 8.3

The convention separates traversal from the data source:

  • Symbol.iterator returns the iterator used by iteration. section 8.3
  • next advances the state and returns a value together with a done flag. section 8.3
  • for...of repeatedly requests values until iteration finishes. section 8.3

A stateful range iterator

function range(start, end) { return { [Symbol.iterator]() { return this; }, next() { return start < end ? { value: start++, done: false } : { value: end, done: true }; } }; } The incremented start variable preserves traversal state between calls. section 8.3

function range(start, end) {
  return {
    [Symbol.iterator]() {                              #1
      return this;
    },
    next() {
      if(start < end) {
        return { value: start++, done:false };         #2
      }
      return { done: true, value:end };                #2
    }
  };
}

Inspect the complete range iterator implementation and its Symbol.iterator and next methods. section 8.3

How Functional Programming in JavaScript covers it

How deep it goes
Explains internal iterator state, protocol methods, generator suspension, and for...of consumption.
Examples
Uses infinite ranges, bounded ranges, square generation, string iteration, and recursive tree traversal.
What it assumes
Builds from JavaScript functions and for...of iteration before connecting generators to iterator behavior.
What you can do after
Build it from scratch with Symbol.iterator and next, or consume generators through for...of.
How it connects
Connects iterators with generators, lazy evaluation, recursion, for...of, and Symbol.iterator.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.