The JavaScript yield keyword
The yield keyword pauses a generator function and hands a value back to the caller. Execution freezes at the yield until the next value is requested, then resumes from that point. yield* delegates to another generator or iterable. yield is only valid inside a function*.
Overview
yield is the keyword that makes generator functions work. When execution reaches yield value, the generator produces that value to whoever called .next() and then pauses; its variables and position are preserved. The next time .next() is called, it picks up exactly where it left off and runs to the following yield.
That suspend-and-resume is what lets a generator produce a sequence over time rather than all at once. You can have multiple yields, yield inside loops, and yield conditionally; each one is a point where the function hands back a value and waits. yield is only valid inside a function*; using it elsewhere is a syntax error.
There are two extra capabilities worth knowing. yield* (yield-delegate) yields every value from another generator or iterable in turn, handy for composing generators or flattening. And yield is actually two-way: the value passed to .next(value) becomes the result of the yield expression inside the generator, allowing the caller to feed data back in (a more advanced pattern). For most uses, though, yield simply means "produce this value and pause."
Syntax
function* gen() {
yield 1; // produce 1, pause
yield 2; // produce 2, pause
yield* [3, 4]; // delegate: produce 3, then 4
}
// the value passed to next() becomes the yield result
// const x = yield prompt; // two-way communication
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
function* greetings() {
yield 'Hello';
yield 'Hola';
yield* ['Bonjour', 'Ciao']; // delegate to an array
}
document.getElementById('out').textContent = [...greetings()].join('\n');
// Hello / Hola / Bonjour / Ciao
</script>
Best practices
- Use
yieldonly inside a function*; it's a syntax error elsewhere. - Each
yieldproduces a value and pauses; use loops to yield a sequence. - Use
yield*to delegate to another generator or iterable. - Remember
.next(value)can pass a value back in as the result of the pausedyield.
Frequently asked questions
What does yield do in JavaScript?
Where can I use yield?
function*). Using it anywhere else is a syntax error.What does yield* do?
Can yield receive a value?
.next(value) becomes the result of the paused yield expression, enabling two-way communication.