Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Generator function: function*

A generator function creates an iterator whose execution can pause at yield and resume through next(). It computes values on demand while preserving local state between successive steps.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

function* name(parameters) {
  yield value;
  return finalValue;
}

The declaration function* name(parameters) { ... } defines a generator function. Calling it creates a new Generator object but does not yet execute the function body. Each object has its own execution state; the first next() starts the body, and yield value delivers a value and pauses execution.

Another next() resumes execution after yield, preserving local variables. Its result has value and done fields: yield produces done: false, while return finalValue finishes the generator with done: true. Without an explicit return, the final value is undefined. After completion, further next() calls return value: undefined and done: true.

A generator object is both an iterator and an iterable. for...of and spread syntax (...) in array literals and function argument lists consume values from yield but exclude the final value from return. Spread in object literals does not advance the generator; it copies the generator object's own enumerable properties. An exhausted generator cannot restart; call the function again instead. An argument to next(value) becomes the result of the paused yield expression; the first next() argument is ignored.

You can also define a generator with an expression such as const make = function* () { yield 1; };, where the function name is optional. There is no generator arrow-function syntax. MDN classifies function* as widely available across browsers since September 2016; check target-browser support separately.

Examples

function* steps() {
  yield 10;
  yield 20;
  return 30;
}

const iterator = steps();
for (let i = 0; i < 4; i++) {
  const { value, done } = iterator.next();
  console.log(`${value} | ${done}`);
}
console.log([...steps()].join(", "));

Result

10 | false
20 | false
30 | true
undefined | true
10, 20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources