The yield* Operator
Description
The yield* operator delegates execution to another generator function or iterable object.
How yield* Work
Instead of yielding a single value like yield does, yield* tells JavaScript to "hop inside" another sequence, pull out all of its individual items one by one, and then come back when it is finished.
The Nesting Analogy
Imagine you are packing boxes for a move.
A normal yield is like putting one individual item into your big moving box.
Using yield* is like also gathering some smaller boxes that are already packed.
Example
// Create a Generator function
function* countToThree() {
yield 1;
yield 2;
yield 3;
}
function* masterGenerator() {
yield "Start";
// Delegate to the countToThree generator
yield* countToThree();
yield "End";
}
const iterator = masterGenerator();
console.log(iterator.next().value); // "Start"
console.log(iterator.next().value); // 1 (Borrowed from countToThree)
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
console.log(iterator.next().value); // "End"
Try it Yourself »
How it Works
You use yield* followed by an iterable (like an array or another generator function).
It loops through that target and yields every single value it finds.
Browser Support
yield* is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |