Delegation with yield*
Learn to delegate to another generator or iterable with yield*.
Delegation with yield*
yield* (with an asterisk) lets you delegate to another generator or iterable. All values from the inner generator are produced by the outer generator as if they were its own. This is a clean way to compose generators.
function* inner() {
yield 1;
yield 2;
}
function* outer() {
yield* inner();
yield 3;
}The values from this are: 1, 2, 3 in order.
Composing generators
With yield* you can compose generators. Each part stays a separate generator; the outer one consumes them in turn. This makes it easy to split a large data stream into smaller pieces.
function* vowels() { yield 'a'; yield 'e'; }
function* consonants() { yield 'b'; yield 'c'; }
function* alphabet() {
yield* vowels();
yield* consonants();
}Result: a, e, b, c — consumable in a single loop.
Exercise Combine two generators
Write a generator named inner that yields 'a' and 'b'. Write a generator named outer that delegates to inner with yield* inner() and then yields 'c'. Iterate outer() with for...of and log each value with console.log.
Show example solution
function* inner() {
yield "a";
yield "b";
}
function* outer() {
yield* inner();
yield "c";
}
for (const v of outer()) {
console.log(v);
}
Test yourself
-
What does yield* do?
- Temporarily pauses the generator
- Returns a Promise
- Produces only a single value
- Delegates to another generator or iterable
Show answer
Delegates to another generator or iterable — Correct! yield* passes all values from the inner generator to the outer one.
-
Add the delegation expression
function* inner() { yield 1; yield 2; } function* outer() { ____ inner(); yield 3; }Show answer
function* inner() { yield 1; yield 2; } function* outer() { yield* inner(); yield 3; } -
Match the delegation terms
- yield*
- delegates to another generator
- yield
- produces one value
- compose
- combines generators