The yield Operator
Description
The yield operator is used to pause and resume a generator function.
How yield Work
To use yield, you must be inside a generator function, which is written with an asterisk like this: function*.
A generator function returns a tracker object called an iterator. Every time you call the .next() method on that iterator, the function runs until it hits a yield statement. It then pauses and gives you back an object.
Tip
yield is the generator version of the return keyword.
Example
// Create a Generator function*
function* countToThree() {
// Pause after each next()
yield "One";
yield "Two";
yield "Three";
// Exit after the 4th next()
return "All done!";
}
// Set up the generator tracker
const counter = countToThree();
// Loop and extract the value from each yield
for (const value of counter) {
text += value + "
";
}
Try it Yourself »
A Simple Analogy
Imagine reading a book.
- A normal function is like reading the whole book until you reach the end (return).
- A generator function is like reading a few pages and putting a bookmark (yield) down to take a break. The next time you open the book (with .next()), you start reading from where you left the bookmark.
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 |