Tech Interview RoomStudy guides

JavaScript

What are generators and iterators? Where are they used?

Advanced · 2 min read · Lesson 11 of 12 in JavaScript

The iteration protocol

  • An iterable has a [Symbol.iterator]() method that returns an iterator.
  • An iterator has next() returning { value, done }.
  • for...of, spread [...x], destructuring, Array.from, Promise.all and new Map(x) all consume iterables. Arrays, strings, Map, Set and NodeList are iterable; plain objects are not.

Generators

A function* returns a generator, which is both an iterator and an iterable. Each yield pauses the function and hands out a value; next(v) resumes it and makes yield evaluate to v. Generators are lazy: values are produced only when asked for, so infinite sequences are fine.

Async iteration

async function* yields promises and is consumed with for await...of. It suits paginated APIs and streams (a ReadableStream is async-iterable in modern runtimes).

Real uses

Lazy pipelines, custom data structures that work with for...of, paginated fetching, and Redux-Saga, which is built on generators.

Example

js
function* ids(start = 1) {
  let id = start;
  while (true) yield id++;               // infinite, but lazy
}
function* take(iter, n) {
  for (const x of iter) {
    if (n-- <= 0) return;
    yield x;
  }
}
console.log([...take(ids(100), 3)]);     // [ 100, 101, 102 ]

class Range {
  constructor(from, to) { this.from = from; this.to = to; }
  *[Symbol.iterator]() { for (let i = this.from; i <= this.to; i++) yield i; }
}
console.log([...new Range(1, 4)]);       // [ 1, 2, 3, 4 ]

Follow-up questions interviewers ask

Try answering each one before you open it.

How would you fetch all pages of an API lazily?
js
async function* allItems(url) {
  while (url) {
    const res = await fetch(url);
    const { items, next } = await res.json();
    yield* items;
    url = next;
  }
}
// for await (const item of allItems('/api/items')) render(item);

The consumer can break early and no further pages are requested.