Iterators and generators

Topic 1 of 4 in Advanced concepts6 min readBeginnerFree course

Overview

Arrays, strings, Maps and Sets all work with for…of and spread because they are iterable: they can hand out their values one at a time through an iterator.

JavaScript
const it = ['a', 'b'][Symbol.iterator]();
it.next(); // { value: 'a', done: false }
it.next(); // { value: 'b', done: false }
it.next(); // { value: undefined, done: true }

for…of simply calls next() until done is true.

The iteration protocol

Two small rules make this work:

  • An iterable is an object with a method under the key Symbol.iterator that returns an iterator.
  • An iterator is an object with a next() method that returns { value, done }.

Everything that “consumes” iterables relies on these rules: for…of, spread ([...x]), destructuring (const [a, b] = x), Array.from(x), new Set(x), new Map(x), Promise.all(x) and more. Make your object iterable and it works with all of them.

An iterator by hand

JavaScript
const countdown = {
  from: 3,
  [Symbol.iterator]() {
    let current = this.from;
    return {
      next() {
        return current > 0
          ? { value: current--, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

[...countdown]; // [3, 2, 1]

It works, but it’s fiddly. Generators make this far simpler.

Generators

Writing iterators by hand is fiddly. A generator function, marked with *, does it for you. Each yield hands out a value and pauses the function until the next one is requested.

JavaScript
function* steps() {
  yield 'Read';
  yield 'Try';
  yield 'Practise';
}

for (const step of steps()) {
  console.log(step);
}

The generator steps() yields ‘Read’, ‘Try’ and ‘Practise’. The first it.next() runs to the first yield and returns value ‘Read’, done false. Each following call resumes and pauses at the next yield. The fourth call finishes the function and returns value undefined, done true.

Calling steps() doesn’t run any of its code yet. It returns a generator object, which is both an iterator and an iterable. Each next() runs the function until the next yield, then freezes it — local variables and all — until the next request.

The countdown from earlier, as a generator:

JavaScript
function* countdown(from) {
  for (let i = from; i > 0; i--) yield i;
}
[...countdown(3)]; // [3, 2, 1]

Lazy and infinite sequences

Because values are made only when asked for, a generator can describe an endless sequence safely:

JavaScript
function* ids() {
  let n = 1;
  while (true) yield `topic-${n++}`;
}

const next = ids();
next.next().value; // 'topic-1'
next.next().value; // 'topic-2'

while (true) would freeze the page in a normal function. In a generator it’s fine, because the function pauses at every yield. Just don’t spread an infinite generator ([...ids()]) — that asks for every value.

Laziness is also efficient: you can chain steps without building big arrays in between. Using range and take from this topic’s exercise:

JavaScript
function* filter(iterable, test) {
  for (const x of iterable) if (test(x)) yield x;
}

function* map(iterable, fn) {
  for (const x of iterable) yield fn(x);
}

const evensSquared = map(filter(range(0, 1_000_000), (n) => n % 2 === 0), (n) => n * n);
[...take(evensSquared, 3)]; // [0, 4, 16] — only the first few numbers are ever checked

Modern browsers also offer iterator helpers built in, such as iterator.map(), .filter(), .take() and .toArray(): ids().take(3).toArray().

yield* and returning

yield* hands over to another iterable, yielding each of its values in turn:

JavaScript
function* allTopics() {
  yield* ['Loops', 'Arrays'];
  yield* steps();
}
[...allTopics()]; // ['Loops', 'Arrays', 'Read', 'Try', 'Practise']

A return inside a generator ends it; the returned value appears with done: true (but for…of ignores it).

Making your own objects iterable

JavaScript
const course = {
  topics: ['Loops', 'Arrays'],
  *[Symbol.iterator]() {
    yield* this.topics;
  },
};

[...course]; // ['Loops', 'Arrays']

The same works in a class, which is a clean way to let people loop over a collection you’ve built:

JavaScript
class Playlist {
  #songs = [];
  add(song) { this.#songs.push(song); return this; }
  *[Symbol.iterator]() { yield* this.#songs; }
}

for (const song of new Playlist().add('A').add('B')) console.log(song);

Async generators

Async generators (async function*) pair with for await…of to stream data such as paginated API results.

JavaScript
async function* allPages(url) {
  while (url) {
    const res = await fetch(url);
    const page = await res.json();
    yield* page.items;
    url = page.next; // null on the last page
  }
}

for await (const item of allPages('/api/items?page=1')) {
  render(item); // items appear as each page arrives
}

The caller just loops; the generator hides all the paging logic.

Exercise

A range generator

Write a generator range(start, end, step = 1) that yields numbers from start up to (not including) end. Then write take(iterable, n) that yields only the first n values of any iterable.

JavaScript
function* range(start, end, step = 1) {
  // your code here
}

function* take(iterable, n) {
  // your code here
}

console.log([...range(0, 10, 3)]); // [0, 3, 6, 9]

Summary

  • An iterable is anything for…of can loop over; it provides an iterator via Symbol.iterator.
  • An iterator has a next() method returning { value, done }.
  • A generator function (function*) pauses at each yield and resumes on the next next().
  • Generators produce values lazily — only when asked — so they can describe infinite sequences.
  • async function* with for await…of streams asynchronous data.