JavaScript Reference ยท Statements and Declarations
The function* declaration
Reference for JavaScript generator functions (function*): yield, lazy sequences, passing values into next(), yield*, and use with for...of and spread.
A generator function, written function*, does not run its body when you call it. Instead it returns a generator object, which is an iterator. Each call to next() runs the body until the next yield, hands out the yielded value, and pauses with all local variables intact.
This makes generators ideal for lazy sequences, custom iteration and step-by-step state machines.
function* count(max) { for (let i = 1; i <= max; i++) yield i; }
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.
Syntax
function* name(params) { statements } const g = function* (params) { statements }; const obj = { *method() {} }; class C { *method() {} }
Return value of the call: a generator object with next(), return() and throw() methods, which is also iterable.
Usage notes
- Nothing runs on call. The body starts at the first
next(). Parameters are bound at call time. yieldpauses;returnfinishes. Areturn valueends the generator and gives{ value, done: true }. That value is ignored byfor...ofand spread.- Two-way communication.
next(x)makes the pausedyieldexpression evaluate tox. The argument of the firstnext()call is ignored. yield*delegates to another iterable or generator and evaluates to its return value.- Single use. A generator object cannot be restarted. Call the generator function again for a fresh sequence.
- Cleanup. Breaking out of a
for...ofloop calls the generator'sreturn(), running itsfinallyblocks. - Arrow functions cannot be generators. There is no
=>*syntax. - Not constructors. Generator functions cannot be called with
new. - Memory. Because values are produced on demand, a generator can represent very large or infinite sequences with constant memory.
Browser support
Generator functions are supported by all current browsers and Node.js. Iterator helper methods on generator objects (such as map() and take()) are newer; check a compatibility table before relying on them.