Combining yield and yield* in the Same Generator
You'll learn how to mix direct yield statements with yield* delegation within a single generator for maximum flexibility.
The Core Idea
A generator doesn't have to choose between yielding values directly or delegating to other iterables—you can do both! This lets you produce some values yourself (yield) while also handing off control to other generators or iterables (yield*) whenever it makes sense. Think of it like a tour guide who sometimes points things out personally and sometimes lets a specialist take over for certain exhibits.
Mixing Both Approaches
function* numbers() {
yield 1;
yield 2;
}
function* mixed() {
yield 'start'; // Direct yield
yield* numbers(); // Delegate to another generator
yield 'middle'; // Back to direct yield
yield* [10, 20]; // Delegate to an array
yield 'end'; // Direct yield again
}
const gen = mixed();
console.log([...gen]);
// ['start', 1, 2, 'middle', 10, 20, 'end']
The generator seamlessly transitions between producing its own values and delegating to other sources. You maintain full control over the sequence and can interleave different sources of data as needed.
Why This Matters
This pattern is powerful for building complex data pipelines. You might yield some header information, then yield* to delegate traversing a tree structure, then yield footer data. It's all about composability—breaking down complex iteration logic into manageable, reusable pieces while still maintaining control where you need it.
Key Takeaway: You can freely mix yield and yield* in the same generator to combine manual value production with delegation, giving you flexible control over complex iteration flows.