This page is the JavaScript Generator Methods index. A generator object has three methods. Each row below links to a full guide with syntax, examples you can run, and FAQs.
Learn what a generator is on /js/generator. Use this page when you need a specific method such as next().
All three are called on a generator object.
First call a function* function to get the object: const gen = myGenerator();. Then use gen.next(), gen.return() or gen.throw().
Syntax
How to Call a Generator Method
Create a generator object, then call the methods on it:
JavaScript
function* demo() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log("cleanup");
}
}
const first = demo();
console.log(first.next().value); // 1 (resume to the next yield)
console.log(first.return("stop").value); // stop (finish early, finally runs)
const second = demo();
second.next();
try {
second.throw(new Error("Oops")); // throw an error at the paused yield
} catch (err) {
console.log("Caught: " + err.message);
}
Browse
JavaScript Generator Methods Table
All method guides in this JavaScript tutorial series (3 tutorials), grouped by what they do.
These language features work together with the three methods. They are not methods you call on a generator object.
Syntax
What it does
function* name() { }
Declares a generator function. Calling it returns a generator object.
yield value
Pauses the generator and hands out a value.
yield* iterable
Hands out every value of another generator or iterable.
for (const x of generator)
Calls next() for you until the generator is done. A break calls return().
[...generator] and Array.from(generator)
Collect all the values of a generator into an array.
*[Symbol.iterator]() { }
A generator method that makes an object work with for...of and spread.
async function*
An async generator, which yields values that arrive over time.
Frequently Asked Questions
Three: next() resumes the generator and returns { value, done }, return() finishes it early, and throw() throws an error at the paused yield. A generator object is also iterable, so it works with for...of and the spread operator.
The Generator page explains the idea: function*, yield, laziness and the loops that use generators. This index lists the method guides so you can jump straight to next(), return() or throw().
No. They are instance methods: you call them on a generator object, as in gen.next(), after creating it with gen = myGenerator(). You do not call them on the generator function itself.
Not always. for...of, the spread operator and Array.from() call next() for you. Call it by hand when you want to send values in, pull only a few values, or look at the done flag.
Start with next(), because every generator uses it. Then read return() to learn about early exit and cleanup, and finish with throw() for error handling.