The JavaScript yield* expression can be used inside a generator function to specify another generator or an iterable object that you can yield values from. It works by iterating over the operand and yielding each value returned by it. For example:
function* bar() {
yield 2;
yield 3;
}
function* foo() {
yield 1;
yield* bar();
yield 4;
}
const iterator = foo();
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
In the example above you can see that when next() is called on foo():
- In case of
yield, the value of the expression following theyieldkeyword is returned, and; - In case of
yield*,yieldis delegated tobar(), andfoo()yields each value returned by it (till it's closed — i.e. whendonereturned bybar()istrue).
This works in a similar way with other kinds of iterables (such as arrays, strings, or arguments objects):
function* foo(...args) {
yield* [1, 2];
yield* '34';
yield* args;
}
const iterator = foo(5, 6);
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: '3', done: false}
console.log(iterator.next()); // {value: '4', done: false}
console.log(iterator.next()); // {value: 5, done: false}
console.log(iterator.next()); // {value: 6, done: false}
console.log(iterator.next()); // {value: undefined, done: true}