Glossary / Generators
Generators
A generator function (function*) creates a generator object that is both an iterator and iterable. Its body pauses at each yield and resumes when the consumer calls next(). Generators make stateful iteration readable and support lazy sequences, parser state machines, and resource-safe traversal.
Execution and control
function* ids() {
let id = 1;
while (true) yield id++;
}
const sequence = ids();
sequence.next(); // { value: 1, done: false }
sequence.next(); // { value: 2, done: false }
Calling the generator function does not run the body. The first next() starts it. A later next(value) supplies a value as the result of the suspended yield expression; the first argument passed to next is ignored because execution has not yielded yet. Calling return(value) completes the generator, while throw(error) injects an exception at the suspension point. try/finally supports cleanup if the consumer stops early.
Generators are synchronous: a yielded value can be a Promise, but the iterator protocol does not automatically await it. Use async generators for asynchronous work. Infinite generators must be consumed with a bound. Avoid using generators to obscure control flow or when a simple array/loop is clearer.
Interview questions
- When does a generator body execute? When the consumer first calls
next(). - What does
next(value)do after a yield? It supplies the value of that suspended yield expression. - How handle early termination cleanup? Use
try/finally; consumers can call iteratorreturn(). - Are generators asynchronous? Not inherently; async generators are a separate construct.