Generator Functions

Difficulty: Advanced

Question

What are generator functions (function*) in JavaScript, how does yield pause and resume execution, and what are their practical use cases?

Answer

A generator function, declared with function*, returns a generator object instead of running its body immediately. Each call to the generator's next() runs the body until the next yield, hands out that value as { value, done: false }, and freezes the function's local state until next() is called again. This makes generators the simplest way to write lazy sequences, custom iterators and pausable workflows.

How pausing and resuming works

  1. Calling gen() does not execute any code. It creates a generator object in the "suspended start" state.
  2. it.next() runs until the first yield expr and returns { value: expr, done: false }.
  3. The next it.next(x) resumes right after that yield, and the yield expression itself evaluates to x. This is two-way communication.
  4. When the function hits return v or the end, next() returns { value: v, done: true } (value is undefined without a return).
  5. it.return(v) ends the generator early (running any finally blocks), and it.throw(err) throws an error at the paused yield.

Note that the argument to the very first next() is ignored, because there is no paused yield to receive it yet.

Generators and the iterator protocol

A generator object is both an iterator (it has next()) and an iterable (its [Symbol.iterator]() returns itself). So it works anywhere an iterable is accepted: for...of, spread [...gen()], destructuring, Array.from, new Set(gen()). Writing *[Symbol.iterator]() { ... } inside a class is the cleanest way to make your own data structure iterable.

One subtlety: for...of ignores the final return value, because it stops as soon as done is true.

Practical use cases

Gotchas

Pausing and resuming a generator. Change the values passed into next(), or exit early with return(), under Tweak.
  1. Calling a generator runs nothing: It returns an iterator paused before the first line.
  2. next() runs to the next yield: yield sends a value out and freezes the function.
  3. next(value) resumes it: The paused yield expression evaluates to the value passed in.
  4. return ends it: The result has done: true; later next() calls give { value: undefined, done: true }.

Code examples

Lazy infinite sequence with a take helper

function* naturals(start = 1) {
  let n = start;
  while (true) yield n++; // never blocks: runs only on demand
}

function* take(count, iterable) {
  if (count <= 0) return;
  for (const value of iterable) {
    yield value;
    if (--count === 0) return; // return() closes the source too
  }
}

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

const squares = map(n => n * n, naturals());
console.log([...take(5, squares)]);

Nothing is computed until spread pulls values, and only five squares are ever produced even though the source is infinite. Composing generators like this avoids intermediate arrays.

next(value), return() and yield* delegation

function* checkout() {
  const coupon = yield 'Enter coupon';
  try {
    yield `Applied ${coupon}`;
    yield 'Paying...';
  } finally {
    console.log('cleanup ran');
  }
}

const flow = checkout();
console.log(flow.next().value);
console.log(flow.next('SWIGGY50').value);
console.log(flow.return('cancelled'));

class Tree {
  constructor(value, children = []) { this.value = value; this.children = children; }
  *[Symbol.iterator]() {
    yield this.value;
    for (const child of this.children) yield* child; // delegate
  }
}
console.log([...new Tree('a', [new Tree('b'), new Tree('c', [new Tree('d')])])]);

The value passed to next becomes the result of the paused yield, and return() ends the generator after running its finally block. yield* delegates to another iterable, which makes recursive tree traversal a few lines.

Key points

Common follow-up questions

Interview tips

Concepts covered

Generator Function, yield, Iterator Protocol, Lazy Evaluation, yield*, Coroutines

More JavaScript Interview questions