Generator composition
Build a larger generator from reusable generator components.
JS Puzzles · Const
yield* composes generators by delegating iteration from an outer generator to an inner generator. The inner generator’s yielded values pass through transparently, and its final return value becomes the yield* expression’s result.
Inside a generator, yield* composes another generator or iterable into the current one. It forwards yielded values outward and makes the delegated iterator's final value available as the expression's result; calls to next() also continue through the delegated iterator.
yield* iterableThe delegated generator's final return value becomes the value of the yield* expression.
yield* to compose a generator from another generator without manually forwarding every yielded value.next is the mechanism for sending a value back into a suspended generator.yield expression evaluates to the value supplied by the caller's next invocation.function* numbers() {
yield 1;
yield 2;
}
function* combined() {
const result = yield* numbers();
return result + 3;
}
const iterator = combined();
console.log([...iterator]);The outer generator transparently yields the delegated generator's values. The delegated generator finishes with undefined here, so the outer return value is not included by the spread operation.
Build a larger generator from reusable generator components.
Expose values from an inner generator without writing a forwarding loop.
Capture an inner generator’s completion value in the outer generator.
yield* solve?yield* lets one generator compose another by iterating over the delegated generator and forwarding its yielded values. This avoids manually writing a loop that yields each inner value.
Follow-up: What does yield* evaluate to? It evaluates to the delegated generator's completion value, namely the value supplied by its final return.
The outer generator pauses while the delegated generator runs, and its externally observed yields are transparently forwarded. The caller can consume the combined sequence as one iterator.
Follow-up: Can the operand be something other than a generator? Yes; the documentation describes delegation to an iterable, so arrays and other iterable values can be used.
yield can carry information in both directions: the outer caller receives yielded values, and an argument passed to next(value) becomes the suspended yield expression's result. Delegation preserves this generator communication model.
Follow-up: What happens when the delegated generator finishes? The yield* expression completes with the inner generator's final return value, allowing the outer generator to use it.
Generatorsgenerator.next(arg)yieldfunction*