Skip to the content

Lesson 75 of 296

Iterators and generators

What you will learn

  • What "iterable" really means
  • The iterator protocol
  • Making your own object iterable
  • Generator functions and yield
  • Lazy and infinite sequences
  • Async iteration with for await...of
On this page

Iterables

An iterable is any object that can be looped over with for...of, spread with ..., or destructured as an array. Built-in iterables: arrays, strings, Maps, Sets, and some browser objects such as NodeList. Plain objects are not iterable.

What makes something iterable is a special method stored under the key Symbol.iterator.

The iterator protocol

  1. Calling obj[Symbol.iterator]() returns an iterator.
  2. An iterator is an object with a next() method.
  3. Each call to next() returns { value, done }.
  4. When there are no more values, it returns { value: undefined, done: true }.
const letters = ["a", "b"];
const it = letters[Symbol.iterator]();

it.next();     { value: "a", done: false }
it.next();     { value: "b", done: false }
it.next();     { value: undefined, done: true }

for...of does exactly this behind the scenes: it calls next() until done is true.

Making your own iterable

const range = {
  from: 1,
  to: 4,

  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        }
        return { value: undefined, done: true };
      }
    };
  }
};

for (const n of range) console.log(n);      1 2 3 4
[...range]                                  [1, 2, 3, 4]

This works, but it is a lot of code. Generators make it much simpler.

Generator functions

A generator function is written with function*. Calling it does not run its body. It returns a generator, which is an iterator. Each call to next() runs the body until the next yield, then pauses, remembering exactly where it stopped.

function* countToThree() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = countToThree();
gen.next();     { value: 1, done: false }
gen.next();     { value: 2, done: false }
gen.next();     { value: 3, done: false }
gen.next();     { value: undefined, done: true }

for (const n of countToThree()) console.log(n);     1 2 3

The range example, rewritten

function* range(from, to, step = 1) {
  for (let i = from; i <= to; i += step) {
    yield i;
  }
}

[...range(1, 10, 3)]       [1, 4, 7, 10]

As the iterator of an object:

const team = {
  members: ["Sam", "Ali", "Nia"],
  *[Symbol.iterator]() {
    yield* this.members;
  }
};
[...team]        ["Sam", "Ali", "Nia"]

yield* hands over to another iterable and yields all its values.

Lazy and infinite sequences

Generators produce values one at a time, only when asked. This is called lazy evaluation. You can describe an endless sequence without running out of memory:

function* idGenerator() {
  let id = 1;
  while (true) {
    yield id++;
  }
}

const ids = idGenerator();
ids.next().value;     1
ids.next().value;     2

while (true) is safe here, because the generator pauses at every yield. Never spread an infinite generator ([...idGenerator()]): it never ends.

Taking only the first few items:

function* take(iterable, count) {
  let i = 0;
  for (const item of iterable) {
    if (i++ >= count) return;
    yield item;
  }
}
[...take(idGenerator(), 3)]      [1, 2, 3]

Sending values in and stopping early

  • gen.next(value) sends a value into the generator; it becomes the result of the paused yield expression.
  • gen.return(value) finishes the generator early.
  • break in a for...of loop also stops the generator (it calls return for you).

Async iteration

Async generators (async function*) can await inside and yield values over time. Use them with for await...of:

async function* fetchPages(url) {
  let next = url;
  while (next) {
    const res = await fetch(next);
    const data = await res.json();
    yield data.items;
    next = data.nextPage;
  }
}

for await (const items of fetchPages("/api/orders?page=1")) {
  console.log(items.length);
}

Good for paginated APIs and streams of data. In Node.js, streams (for example reading a big file line by line) can be read with for await...of (Part 15).

Where you will meet these

  • for...of, spread and destructuring all use the iterator protocol.
  • Map.entries(), Object.entries() style methods and array.keys() return iterators.
  • Async iteration over streams and paginated data.
  • Some libraries (such as redux-saga) are built on generators.
  • Day to day, you will write generators rarely. Interviewers use them to test deeper understanding.

Common mistakes

  • Expecting a generator function to run when called (it only creates the generator).
  • Spreading an infinite generator.
  • Reusing a finished generator: once done is true, it stays finished. Call the generator function again for a new one.
  • Using for...of instead of for await...of with async generators.

How to say it in an interview

"An object is iterable if it has a Symbol.iterator method that returns an iterator, an object with a next method returning value and done. for...of, spread and array destructuring all use this protocol. Generator functions, declared with function star, return iterators and pause at each yield, resuming on the next call, so they are a simple way to make custom iterables and lazy or infinite sequences. Async generators with for await...of are useful for paginated APIs and streams."

Key words

WordMeaning
IterableAn object that can be used with for...of
IteratorAn object with a next() method
Iterator protocolThe rules: next() returns { value, done }
Symbol.iteratorThe key of the method that makes an object iterable
Generator functionA function* that can pause with yield
yieldPause and hand out a value
Lazy evaluationProducing values only when they are needed
for await...ofA loop over async iterables

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.