Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Operators

The yield operator

Reference for the JavaScript yield and yield* operators: pausing generators, passing values in with next(), delegation to iterables, return() and throw().

yield pauses a generator function and hands a value to whoever called next(). The generator's local state stays intact, and the next call to next() resumes right after the yield. The expression yield x also evaluates to the value passed to the next next(value) call, which gives you two-way communication.

yield* delegates to another iterable or generator: every value it produces is yielded in turn, and the expression evaluates to the delegate's return value.

JavaScript
function* count() {
  yield 1;
  yield 2;
}

Try it

JS Yielding values lazily

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS yield*, return() and throw()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
yield expression
yield              // yields undefined
yield* iterable
const received = yield value;
Part Description
yield value Pauses the generator and makes next() return { value, done: false }.
received = yield ... The result is the argument of the following next(arg) call (undefined if none).
yield* iterable Iterates the iterable and yields each of its values. The result is that iterator's return value (undefined for arrays, strings and most iterables).

Return value: the value sent in by the next next(). For yield*, the delegate's final return value.

Exceptions: yield is only valid inside a function* body (not in nested ordinary functions or arrows). generator.throw(err) raises err at the paused yield. generator.return(v) acts like a return there, running finally blocks.

Usage notes

  • Lazy evaluation. Nothing runs until the first next(). Infinite sequences are safe as long as consumers stop (break, take-style helpers, destructuring).
  • The first next() argument is ignored, since no yield is waiting for it.
  • for...of ignores the return value. Only yielded values are visited; a final return x is reported by next() as { value: x, done: true } but skipped by loops and spread.
  • Cleanup. Breaking out of a for...of calls return() on the generator, which runs finally blocks.
  • Precedence. yield has very low precedence: yield a, b yields a only. Parenthesize when using it inside larger expressions: const x = (yield a) + 1;.
  • yield is not allowed in arrow functions. Wrap a generator in a normal function if you need this.
  • Async generators (async function*) can await and yield; consume them with for await...of.
  • Recursion with yield* is the neat way to traverse trees.

Browser support

Generators and yield are supported in every current browser (ES2015). Async generators (ES2018) are supported in current browsers as well.