Flattening Nested Generators with yield*
What you'll learn: How yield* automatically flattens values from nested generators, creating seamless multi-level iteration.
The Problem with Manual Nesting
You already know that yield* can delegate to another iterable. But one of its most powerful uses is flattening nested generator calls. Without yield*, manually yielding from nested generators requires explicit loops that clutter your code.
Imagine you have a generator that calls other generators. Without yield*, you'd need to manually loop through each nested generator's values:
function* inner() {
yield 1;
yield 2;
}
function* outer() {
for (let val of inner()) {
yield val; // Manual forwarding
}
yield 3;
}
This works, but it's repetitive and error-prone when nesting gets deeper.
How yield* Flattens Automatically
Using yield*, the delegation is transparent—all values flow through as if they came from a single source:
function* inner() {
yield 1;
yield 2;
}
function* outer() {
yield* inner(); // Automatically yields 1, then 2
yield 3;
}
for (let value of outer()) {
console.log(value); // 1, 2, 3
}
The yield* operator "flattens" the nested generator, making outer() behave as if all yields were written directly inside it.
Deep Nesting Example
You can nest generators multiple levels deep:
function* deepest() {
yield 'a';
}
function* middle() {
yield* deepest();
yield 'b';
}
function* top() {
yield* middle();
yield 'c';
}
console.log([...top()]); // ['a', 'b', 'c']
Key Takeaway: yield* transparently flattens nested generator calls, eliminating the need for manual loops and making multi-level iteration feel like a single, unified sequence.