yield* with Arrays and Other Iterables
You'll learn how yield* can delegate to any iterable, not just other generators.
The Power of Universal Delegation
You already know that yield* can delegate to another generator. But here's the key insight: yield* works with any iterable — arrays, strings, sets, maps, or anything implementing the iterator protocol.
When you use yield* with an array or string, the generator automatically yields each element one by one, as if you had written individual yield statements for each item.
How It Works
function* yieldArray() {
yield* [1, 2, 3];
yield* 'hi';
}
const gen = yieldArray();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
console.log(gen.next().value); // 'h'
console.log(gen.next().value); // 'i'
console.log(gen.next().done); // true
Instead of yielding the array [1, 2, 3] as a single value, yield* [1, 2, 3] unpacks it and yields 1, then 2, then 3 individually. Same with the string — each character is yielded separately.
Why This Matters
Think of yield* as a "merge lanes" sign on a highway. It lets you seamlessly blend values from any iterable into your generator's output stream without manually looping:
function* combine() {
yield* [10, 20];
yield* new Set([30, 40]);
yield 50;
}
console.log([...combine()]); // [10, 20, 30, 40, 50]
Key Takeaway: yield* delegates to any iterable (arrays, strings, sets, etc.), automatically yielding each element in sequence — a clean way to incorporate built-in collections into generator output.