Generator Delegation (yield*)
Delegates part of a generator's iteration to another iterable, forwarding values and the delegate's return value transparently.
yield* iterable
Purpose
yield* delegates a generator’s iteration to another iterable — most often another generator —
forwarding each yielded value in place, and capturing the delegate’s return value as the expression’s
own result.
Syntax
function* inner() {
yield 1;
yield 2;
return 'inner done';
}
function* outer() {
const result = yield* inner(); // delegates entirely to inner()
console.log(result); // "inner done"
yield 3;
}
[...outer()]; // [1, 2, 3]
Behavior notes
yield*works on any iterable, not only another generator —yield* [1, 2, 3]oryield* someMap.values()both work.- A value passed into
.next(value)while paused inside a delegated generator is forwarded to that delegate, not the outer generator — full two-way communication passes through transparently. - A thrown error is also forwarded into the delegate first, giving it a chance to handle it via its
own
try/catch, before propagating further if unhandled. - This composability is what makes generators usable as coroutine-like building blocks — a larger staged process built from smaller, independently-defined generators, each delegating to the next.
Common mistakes
- Using a manual
for...ofloop with individualyieldcalls whenyield*would delegate more simply and also forward the delegate’s return value (a manual loop discards it). - Forgetting that
yield*’s own expression value is the delegate’s return value, not its last yielded value — a common source of confusion when refactoring toward delegation.
Runtime notes
Core ECMAScript (ES2015), identical behavior across every current browser and Node version.