function*
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
Thefunction* declaration creates abinding of a new generator function to a given name. A generator function can be exited and later re-entered, with its context (variablebindings) saved across re-entrances.
You can also define generator functions using thefunction* expression.
In this article
Try it
function* generator(i) { yield i; yield i + 10;}const gen = generator(10);console.log(gen.next().value);// Expected output: 10console.log(gen.next().value);// Expected output: 20Syntax
function* name(param0) { statements}function* name(param0, param1) { statements}function* name(param0, param1, /* …, */ paramN) { statements}Note:Generator functions do not have arrow function counterparts.
Note:function and* are separate tokens, so they can be separated bywhitespace or line terminators.
Parameters
nameThe function name.
paramOptionalThe name of a formal parameter for the function. For the parameters' syntax, see theFunctions reference.
statementsOptionalThe statements comprising the body of the function.
Description
Afunction* declaration creates aGeneratorFunction object. Each time a generator function is called, it returns a newGenerator object, which conforms to theiterator protocol. The generator function's execution issuspended at some place, which is initially at the very beginning of the function body. The generator function can be called multiple times to create multiple generators simultaneously; every generator maintains its ownexecution context of the generator function and can be stepped independently.
The generator allows bidirectional control flow: control flow can transfer between the generator function (callee) and its caller as many times as both parties wish to. Control flow can go from the caller to the callee by calling the generator's methods:next(),throw(), andreturn(). Control flow can go from the callee to the caller by exiting the function as normal usingreturn orthrow or execution all statements, or by using theyield andyield* expressions.
When the generator'snext() method is called, the generator function's body is executed until one of the following:
- A
yieldexpression. In this case, thenext()method returns an object with avalueproperty containing the yielded value and adoneproperty that is alwaysfalse. The next timenext()is called, theyieldexpression evaluates to the value passed tonext(). - A
yield*, delegating to another iterator. In this case, this call and any future calls tonext()on the generator is the same as callingnext()on the delegated iterator, until the delegated iterator is finished. - A
returnstatement (that is not intercepted by atry...catch...finally), or the end of the control flow which implicitly meansreturn undefined. In this case, the generator is finished, and thenext()method returns an object with avalueproperty containing the returned value and adoneproperty that is alwaystrue. Any furthernext()calls have no effect and always return{ value: undefined, done: true }. - An error thrown inside the function, either via a
throwstatement or an unhandled exception. Thenext()method throws that error, and the generator is finished. Any furthernext()calls have no effect and always return{ value: undefined, done: true }.
When the generator'sthrow() method is called, it acts as if athrow statement is inserted in the generator's body at the current suspended position. Similarly, when the generator'sreturn() method is called, it acts as if areturn statement is inserted in the generator's body at the current suspended position. Both methods usually finish the generator, unless the generator function catches the completion viatry...catch...finally.
Generators used to be a paradigm for asynchronous programming, avoidingCallback Hell by achievingInversion of Control. Nowadays, this use case is solved with the simplerasync functions model and thePromise object. However, generators are still useful for many other tasks, such as definingiterators in a straightforward way.
function* declarations behave similar tofunction declarations — they arehoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.
Examples
>Basic example
function* idMaker() { let index = 0; while (true) { yield index++; }}const gen = idMaker();console.log(gen.next().value); // 0console.log(gen.next().value); // 1console.log(gen.next().value); // 2console.log(gen.next().value); // 3// …Example with yield*
function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3;}function* generator(i) { yield i; yield* anotherGenerator(i); yield i + 10;}const gen = generator(10);console.log(gen.next().value); // 10console.log(gen.next().value); // 11console.log(gen.next().value); // 12console.log(gen.next().value); // 13console.log(gen.next().value); // 20Passing arguments into Generators
function* logGenerator() { console.log(0); console.log(1, yield); console.log(2, yield); console.log(3, yield);}const gen = logGenerator();// the first call of next executes from the start of the function// until the first yield statementgen.next(); // 0gen.next("pretzel"); // 1 pretzelgen.next("california"); // 2 californiagen.next("mayonnaise"); // 3 mayonnaiseReturn statement in a generator
function* yieldAndReturn() { yield "Y"; return "R"; yield "unreachable";}const gen = yieldAndReturn();console.log(gen.next()); // { value: "Y", done: false }console.log(gen.next()); // { value: "R", done: true }console.log(gen.next()); // { value: undefined, done: true }Generator as an object property
const someObj = { *generator() { yield "a"; yield "b"; },};const gen = someObj.generator();console.log(gen.next()); // { value: 'a', done: false }console.log(gen.next()); // { value: 'b', done: false }console.log(gen.next()); // { value: undefined, done: true }Generator as an object method
class Foo { *generator() { yield 1; yield 2; yield 3; }}const f = new Foo();const gen = f.generator();console.log(gen.next()); // { value: 1, done: false }console.log(gen.next()); // { value: 2, done: false }console.log(gen.next()); // { value: 3, done: false }console.log(gen.next()); // { value: undefined, done: true }Generator as a computed property
class Foo { *[Symbol.iterator]() { yield 1; yield 2; }}const SomeObj = { *[Symbol.iterator]() { yield "a"; yield "b"; },};console.log(Array.from(new Foo())); // [ 1, 2 ]console.log(Array.from(SomeObj)); // [ 'a', 'b' ]Generators are not constructable
function* f() {}const obj = new f(); // throws "TypeError: f is not a constructorGenerator example
function* powers(n) { // Endless loop to generate for (let current = n; ; current *= n) { yield current; }}for (const power of powers(2)) { // Controlling generator if (power > 32) { break; } console.log(power); // 2 // 4 // 8 // 16 // 32}Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-generator-function-definitions> |
Browser compatibility
See also
- Functions guide
- Iterators and generators guide
- Functions
GeneratorFunctionfunction*expressionfunctionasync functionasync function*- Iteration protocols
yieldyield*Generator- Regenerator on GitHub
- Promises and Generators: control flow utopia presentation by Forbes Lindesay at JSConf (2013)
- Task.js on GitHub
- You Don't Know JS: Async & Performance, Ch.4: Generators by Kyle Simpson