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();
let text = "";
for (const value of masterGenerator()) {
text += value;
}
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.
You Can Use It With Arrays Too!
Because yield* works with any iterable object, you can use it as a shortcut to unload regular JavaScript arrays or strings without writing a messy loop.
Example
// Create an Array
const food = ["Milk", "Bread", "Eggs"];
function* groceryList() {
yield "Apples";
// Loop the array
yield* food;
yield "Chocolate";
}
for (const item of groceryList()) {
text += item;
}
Try it Yourself »
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 |