Sub topic 11
Delegating with yield*
This chapter assumes you already know how generator functions work: function*, yield, lazy start, and how a generator pauses and resumes. It also assumes you have used generators as the Symbol.iterator method of a class. Here you will learn yield*, which lets one generator hand control to another iterable until that iterable is finished.
The problem yield* solves
Generators often need to produce values that come from somewhere else. A tree yields its own value and then every value from each child. A combined list yields everything from list A and then everything from list B. You can write that with a loop:
function* concat(a, b) {
for (const x of a) yield x;
for (const x of b) yield x;
}
console.log([...concat([1, 2], 'ab')]); // [ 1, 2, 'a', 'b' ]That loop works for simple cases. yield* says the same thing in one expression, and it also forwards details that the loop drops: the return value of the inner generator, and calls to next(value), throw(), and return().
function* concat(a, b) {
yield* a;
yield* b;
}
console.log([...concat([1, 2], 'ab')]); // [ 1, 2, 'a', 'b' ]What yield* does
yield* expr takes any iterable. It does not have to be a generator. It does three things:
- It calls
expr[Symbol.iterator]()to get an iterator. - It passes each value from that iterator straight out to whoever is consuming the outer generator. The outer generator stays paused at the
yield*the whole time. - When the inner iterator reports
done: true, theyield*expression evaluates to that final result'svalue, and the outer generator continues from there.
function* inner() {
yield 'a';
yield 'b';
return 'inner done';
}
function* outer() {
const result = yield* inner();
yield result;
yield* [1, 2];
}
console.log([...outer()]); // [ 'a', 'b', 'inner done', 1, 2 ]The string 'inner done' comes with done: true, so the spread operator never sees it as an item. yield* catches it, the outer generator stores it in result, and then yields it as an ordinary value. For arrays, strings, Maps, and other built-in iterables the final value is undefined, so yield* [1, 2] evaluates to undefined.
Recursion: walking a tree
yield* is most useful for recursive structures. Each node yields its own value and then delegates to its children. Each child delegates to its own children in the same way.
class TreeNode {
constructor(value, children = []) {
this.value = value;
this.children = children;
}
*[Symbol.iterator]() {
yield this.value;
for (const child of this.children) {
yield* child; // uses child[Symbol.iterator]
}
}
}
const tree = new TreeNode('root', [
new TreeNode('a', [new TreeNode('a1'), new TreeNode('a2')]),
new TreeNode('b')
]);
console.log([...tree]); // [ 'root', 'a', 'a1', 'a2', 'b' ]You can delegate to child directly because TreeNode is iterable. You don't need to write child[Symbol.iterator]() yourself.
A recursive generator to flatten nested arrays follows the same pattern:
function* flatten(value) {
if (Array.isArray(value)) {
for (const item of value) yield* flatten(item);
} else {
yield value;
}
}
console.log([...flatten([1, [2, [3, [4]]], 5])]); // [ 1, 2, 3, 4, 5 ]Forwarding next(), throw(), and return()
While yield* is active, the outer generator forwards things to the inner iterator. It passes along more than the values coming out. Method calls going in are forwarded as well. The next chapter covers next(value), throw(), and return() in detail. The point here is that yield* forwards all three, and a hand-written loop forwards none of them.
function* inner() {
try {
const reply = yield 'question';
console.log('inner got:', reply);
yield 'more';
} finally {
console.log('inner cleanup');
}
}
function* delegating() {
yield* inner();
}
const g = delegating();
console.log(g.next()); // { value: 'question', done: false }
console.log(g.next('hi')); // logs "inner got: hi", then { value: 'more', done: false }
console.log(g.return('x')); // logs "inner cleanup", then { value: 'x', done: true }Now replace yield* inner() with a loop:
function* looping() {
for (const x of inner()) yield x;
}
const h = looping();
h.next();
h.next('hi'); // logs "inner got: undefined"
h.return('x'); // logs "inner cleanup"The loop drops the 'hi' because for...of always calls next() with no argument. Cleanup still runs in this case only because for...of calls the inner iterator's return() when the loop exits early. A throw() sent to looping would be raised at the yield x line in the outer generator. The inner generator would see it only as an early return, not as an error it can catch.
| Form | Values come out | Inner return value | next(value) reaches inner | throw() reaches inner |
|---|---|---|---|---|
| `yield iterable` | The iterable itself, as one value | Not applicable | No | No |
| `for (const x of it) yield x` | Yes | Lost | No | No, the inner is only closed |
| `yield* it` | Yes | Result of the expression | Yes | Yes, if the inner has `throw()` |
Common errors
Writing yield instead of yield*
function* wrong() {
yield [1, 2];
}
console.log([...wrong()]); // [ [ 1, 2 ] ]Plain yield produces the array as a single value. If you delegate to a generator by mistake this way, you get a generator object in your output instead of its values.
Delegating to something that is not iterable
function* bad() {
yield* { a: 1 };
}
try {
[...bad()];
} catch (e) {
console.log(e instanceof TypeError); // true
}Plain objects have no Symbol.iterator. Use Object.entries(obj) or Object.values(obj) to get an array first. Watch out for null and undefined too, which throw the same TypeError.
Using yield* inside a callback
yield and yield* work only directly inside the generator's own body. This is a syntax error:
// SyntaxError: callbacks are not generators
// function* broken(lists) {
// lists.forEach(list => { yield* list; });
// }Use a for...of loop in the generator body instead:
function* fixed(lists) {
for (const list of lists) yield* list;
}
console.log([...fixed([[1], [2, 3]])]); // [ 1, 2, 3 ]Delegating to a one-shot iterator twice
yield* someArray gets a fresh iterator each time. A generator object can be used only once, so delegating to the same generator object a second time yields nothing:
const once = (function* () { yield 1; })();
function* twice() {
yield* once;
yield* once;
}
console.log([...twice()]); // [ 1 ]Call the generator function again (yield* makeGen()) when you need the values a second time.
Exercise
What does this code print? function letters() { yield 'x'; yield 'y'; return 'L'; } function numbers() { yield 1; return 'N'; } function all() { const a = yield letters(); const b = yield numbers(); const c = yield 'ok'; return [a, b, c]; } const g = all(); console.log([...g]); console.log(g.next());
Show answer
The first log prints [ 'x', 'y', 1, 'o', 'k' ]. The values 'L' and 'N' become a and b, and c is undefined because a string iterator finishes with value undefined. Spread ignores the final [ 'L', 'N', undefined ] because it arrives with done: true, and that consumes the generator. The second log therefore prints { value: undefined, done: true }.
Exercise
Write a generator function interleave(a, b) that is not recursive and does not use yield. It should yield before, then every value of iterable a, then between, then every value of b, then after. Then rewrite it with yield. Which version keeps working if a is a generator that reads values sent with next(value)?
Show answer
Loop version: function interleave(a, b) { yield 'before'; for (const x of a) yield x; yield 'between'; for (const x of b) yield x; yield 'after'; }. Delegating version: function interleave(a, b) { yield 'before'; yield a; yield 'between'; yield b; yield 'after'; }. Only the yield* version works in that case. It forwards next(value), throw(), and return() to a, while the for...of loop always calls next() with no argument, so a would receive undefined.