All topics
ES6+advanced

Generator Functions

Functions that can pause and resume execution using yield, producing values lazily one at a time and automatically implementing the iterator protocol.

Generator functions, declared with function*, are a distinct kind of function that can pause its own execution at a yield expression and later resume exactly where it left off, rather than running to completion in one call. They underpin async generators, lazy sequences, and were the mechanism early async/await polyfills used before native support existed.

A generator function is like a bookmark in a very long book: instead of reading the whole book in one sitting, you read one chapter, hand it over, and put in a bookmark — the book remembers exactly where you stopped.

Key Concepts

1
Calling a generator function doesn't execute its body immediately; it returns a generator object, which is both an iterator and an iterable. Each call to .next() runs the generator's body from wherever it last paused up to the next yield, returning {value, done: false}; the generator's internal state is fully preserved between calls.
2
This pause-and-resume mechanic makes generators ideal for representing lazy, potentially infinite sequences — a generator can yield values forever inside an infinite loop, and the consumer decides how many values to pull. .next(value) can also pass a value into the generator, becoming the result of the paused yield expression, enabling two-way communication.
3
Generators are also the underlying mechanism async generators build on, and since they automatically implement the iterator protocol, they're the easiest way to make a custom object iterable.