Skip to the page

Symbols, iterators, generators and Proxy · senior

Generators

A generator function (function*) returns an iterator that runs its body only on demand and pauses at each yield; next(value) resumes it and sends a value in, which makes generators good for lazy sequences, pausable flows and, in async form, streaming data.

The notes

What you must know

  • Calling a generator function runs nothing; it returns a generator object that is both an iterator and an iterable.
  • next(v) resumes the body; v becomes the result of the paused yield expression. The argument of the first next() is ignored because no yield is waiting yet.
  • return(v) ends the generator (finally blocks still run); throw(err) throws at the paused yield.
  • yield* delegates to another iterable or generator (useful for recursive tree walks).
  • A return x inside the generator gives { value: x, done: true }; for...of and spread ignore that final value.
  • Uses: lazy or infinite sequences, ID generators, tree traversal, redux-saga effects, splitting long work into steps.
  • async/await is conceptually a generator plus a runner that resumes it when each promise settles.

The red pen

Common traps: mistake → fix

  • Mistake: The first next(5) sets x in const x = yield 1

    Fix: the first next only starts the body; its argument is lost.

  • Mistake: for...of receives the generator's return value

    Fix: it stops at done: true and ignores it.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a generator?
  2. Predict two-way communication with next(value).
  3. How do return() and throw() work? What happens to finally blocks?
  4. Walk a tree with yield*.
  5. Build a tiny run() that makes a generator behave like async/await.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview