JavaScript Reference ยท Iterators, Generators and Symbols
Generator objects
Reference for JavaScript generator objects: next(value), return() and throw() methods, how yield pauses a generator, finally blocks, and one-shot behavior.
Calling a generator function (function*) does not run its body. It returns a generator object, which is an iterator you drive by hand or with for...of. The body runs only when you call next(), and it pauses at each yield.
A generator object has three methods, next(), return() and throw(), and it is its own iterable, so [Symbol.iterator]() returns itself. See function* for how to declare one and yield for the operator.
function* numbers() { yield 1; yield 2; } const generator = numbers(); generator.next(); // { value: 1, done: false }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Methods
| Method | Description |
|---|---|
next(value) |
Resumes the generator. The value becomes the result of the yield expression it was paused on (ignored on the first call). Returns { value, done }. |
return(value) |
Finishes the generator early at the paused yield, running any finally blocks. Returns { value, done: true }. |
throw(error) |
Throws error at the paused yield. If the generator catches it, it continues and returns the next yielded result; otherwise the error propagates to the caller and the generator finishes. |
States
A generator is suspended-start, suspended-yield, executing or completed.
- The first
next()starts the body and runs to the firstyield; the argument to that first call has nowhere to go and is dropped. - After completion (by
returnstatement, falling off the end,return()or an uncaught error), everynext()returns{ value: undefined, done: true }. - A
returnstatement inside the generator produces a final result withdone: true.for...ofand spread ignore that final value. - Calling
next()while the generator is already running (re-entrance) throws aTypeError.
Usage notes
- Lazy evaluation. Nothing runs until requested, so generators can model infinite sequences. Always limit them with
break,take()or a counter. - One-shot. A generator object cannot be restarted. Call the generator function again for a fresh one.
finallyblocks run onreturn()and onbreakout of afor...ofloop (which callsreturn()for you), but not if the generator is simply abandoned.yield*delegates to another iterable or generator, forwardingnext(),return()andthrow()to it.return()can be overridden by ayieldinsidefinally; the generator then stays alive.- Generators cannot be arrow functions, and
newcannot be used with them. - Methods:
*name() {}in objects and classes, andstatic *name() {}.
Browser support
Generators have been available since ES2015 in all current browsers and Node.js.