Delegate sequences with yield*
Quick answer
yield* delegates iteration to another iterable, forwarding its yielded values rather than yielding the iterable itself.
How it works
In a synchronous generator, yield* iterable obtains a synchronous iterator. Values are forwarded in sequence. The expression evaluates to the delegate’s final done-true value. Delegation forwards next inputs and handles return and throw according to the delegate’s methods. A normal yield iterable instead produces one value. Use delegation to combine small sequences without eagerly allocating arrays.
function* g(){yield 1;yield* [2,3];yield 4;} console.log(JSON.stringify([...g()]));Expected output in Node.js:
[1,2,3,4]The delegated array contributes individual values.
function* inner(){yield 2;return 7;} function* outer(){const n=yield* inner();yield n+1;} console.log(JSON.stringify([...outer()]));Expected output in Node.js:
[2,8]The final inner value becomes the value of the yield* expression.
Common mistakes
Do not delegate to a noniterable number. The delegate’s return value is not automatically yielded.
Practice
Combine two sequences using yield* and capture the completion value of an inner generator.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Delegate sequences with yield* — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
What does yield* do with an ordinary array?
What is the value of a completed yield* expression?
Which input is invalid for synchronous yield*?
What is the exact console output in Delegate sequences with yield* example 1?
function* g(){yield 1;yield* [2,3];yield 4;} console.log(JSON.stringify([...g()]));What is the exact console output in Delegate sequences with yield* example 2?
function* inner(){yield 2;return 7;} function* outer(){const n=yield* inner();yield n+1;} console.log(JSON.stringify([...outer()]));