← Back to JavaScript, page 2

javascript-0021 · Hard senior

What are generators in JavaScript, and how do they relate to the iterator protocol?

A generator is a function declared with function* that can pause at yield and be resumed later, producing values on demand. Calling it returns a generator object that follows the iterator protocol, so for...of, spread, and destructuring work with it. Generators allow lazy sequences, infinite streams, and two-way communication through next(value).

Full answer

An iterator is any object with a next() method that returns { value, done }. An iterable is an object with a [Symbol.iterator]() method that returns an iterator. for...of, spread, Array.from, and destructuring all work on iterables.

A generator function, written function*, is a shortcut for building iterators. Calling it does not run the body. It returns a generator object, which is both an iterator and an iterable. Each next() runs the body until the next yield, hands out that value, and freezes the function with all its local variables. The next call continues from the same place. When the function ends, done becomes true, and the return value is reported once.

Because values are produced on demand, a generator can describe an infinite sequence safely, as long as the consumer stops. This lazy behavior saves memory when a large list would otherwise have to be built first.

Generators are two-way. next(x) makes the paused yield expression evaluate to x. throw(error) raises an error at the pause, and return(value) ends the generator early, running any finally blocks. yield* delegates to another iterable.

Async generators (async function*) yield promises and are consumed with for await...of. They fit paginated APIs and streams.

javascript
function* idGenerator(prefix) {
  let n = 1;
  while (true) {
    yield `${prefix}-${n++}`;
  }
}

function* take(iterable, count) {
  if (count <= 0) return;
  let seen = 0;
  for (const item of iterable) {
    yield item;
    if (++seen >= count) return;
  }
}

console.log([...take(idGenerator('STU'), 3)]);

const gen = idGenerator('ROLL');
console.log(gen.next(), gen.next().value);

function* conversation() {
  const name = yield 'What is your name?';
  const city = yield `Hi ${name}, which city?`;
  return `${name} from ${city}`;
}
const chat = conversation();
console.log(chat.next().value);
console.log(chat.next('Zoya').value);
console.log(chat.next('Pune'));

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

async function* pages() {
  for (let page = 1; page <= 2; page++) {
    await new Promise((resolve) => setTimeout(resolve, 5));
    yield `page ${page}`;
  }
}
(async () => {
  for await (const page of pages()) console.log(page);
})();

Run with Node.js v24.22.1 as js-21.js; two runs gave identical output. Output: [ 'STU-1', 'STU-2', 'STU-3' ] { value: 'ROLL-1', done: false } ROLL-2 What is your name? Hi Zoya, which city? { value: 'Zoya from Pune', done: true } [ 3, 2, 1 ] page 1 page 2

Key points

  • An iterator has next() returning { value, done }; an iterable has Symbol.iterator.
  • function* returns a generator object that is both.
  • yield pauses and keeps local state; next resumes.
  • Generators are lazy, so infinite sequences are possible.
  • next(value), throw, return, and yield* give two-way control; async generators work with for await.

Common mistakes

  • Spreading or looping over an infinite generator without a stop condition, which never finishes.
  • Reusing a finished generator. Once done is true, it stays done; call the function again for a new one.
  • Forgetting that the first next(value) argument is ignored, because no yield is waiting yet.
  • Using a generator when a plain array is simpler and the data is small.

Follow-ups

  • How does yield* differ from yielding each item in a loop?
  • What does return() do to a generator that is paused inside a try...finally?
  • How would you consume a paginated API with an async generator?

Tips

  • Explain iterator and iterable first. It makes the generator part simple.
  • Use an id generator or pagination as an example; both are realistic.
  • Mention laziness and memory, then mention two-way next(value) for extra depth.