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.
function* count() { yield 1; yield 2; }
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
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 noyieldis waiting for it. for...ofignores the return value. Onlyyielded values are visited; a finalreturn xis reported bynext()as{ value: x, done: true }but skipped by loops and spread.- Cleanup. Breaking out of a
for...ofcallsreturn()on the generator, which runsfinallyblocks. - Precedence.
yieldhas very low precedence:yield a, byieldsaonly. Parenthesize when using it inside larger expressions:const x = (yield a) + 1;. yieldis not allowed in arrow functions. Wrap a generator in a normal function if you needthis.- Async generators (
async function*) canawaitandyield; consume them withfor 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.