Difficulty: Advanced
What are generator functions (function*) in JavaScript, how does yield pause and resume execution, and what are their practical use cases?
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.
gen() does not execute any code. It creates a generator object in the "suspended start" state.it.next() runs until the first yield expr and returns { value: expr, done: false }.it.next(x) resumes right after that yield, and the yield expression itself evaluates to x. This is two-way communication.return v or the end, next() returns { value: v, done: true } (value is undefined without a return).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.
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.
take(5, naturals()) is cheap.yield* recursion.map, filter, take over generators to process large data without building intermediate arrays.co and Redux-Saga use generators to write async code that looks synchronous. async/await largely replaced the co pattern, but Redux-Saga still uses generators because effects can be tested by stepping through next().for...of produces nothing.* arrow syntax.yield is only valid directly inside the generator body, not inside a nested callback such as forEach.for...of calls return() on the generator, so finally blocks run. That is useful for cleanup.async function* with for await...of), which are a separate feature.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.
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.
Generator Function, yield, Iterator Protocol, Lazy Evaluation, yield*, Coroutines