Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

yield — suspending a generator

The `yield` expression suspends a generator and exposes a value to its consumer. A subsequent `next(value)` resumes execution and supplies a value to the suspended expression; `yield*` delegates iteration.

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

yield;
yield expression;
yield* iterable;

yield expression suspends a generator while preserving its state. In a synchronous generator, next() then returns { value, done: false }. Bare yield exposes undefined. Calling a function* function creates a generator; its body starts running only on the first next().

The argument to a subsequent next(value) becomes the result of the suspended yield expression. The first next() argument is ignored. When the generator finishes with return value, the result is { value, done: true }. If return value exits a try block and the corresponding finally block executes a yield, the generator can suspend again with a result whose done is false before the pending return completes.

yield* iterable delegates iteration and forwards yielded values; the expression's result is the delegated iterator's final value. yield expressions are allowed in synchronous and asynchronous generator bodies, but not in their parameters or in nested ordinary or arrow functions. In asynchronous generators, next() returns a promise for an iteration result.

Do not put a line break between yield and its operand or *: this can change parsing or cause a syntax error. yield cannot be an identifier in strict code or in grammar contexts reserved for generators; some other non-strict contexts permit it.

Examples

function* exchange() {
  const received = yield 10;
  yield received + 1;
  return 99;
}

const iterator = exchange();
for (const result of [iterator.next(), iterator.next(20), iterator.next()]) {
  console.log(JSON.stringify(result));
}

Result

{"value":10,"done":false}
{"value":21,"done":false}
{"value":99,"done":true}

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