yield
Pauses a generator function and produces a value to its caller.
Syntax
yield expression;
yield* iterable;
Returns
any — The value passed to the generator's `next()` call that resumes
execution.
Examples
function* count() {
yield 1;
yield 2;
yield 3;
}
console.log([...count()]);
Output
[ 1, 2, 3 ]
function* gen() {
const x = yield "first";
console.log("received", x);
}
const g = gen();
console.log(g.next().value);
g.next("hello");
Output
first
received hello
function* inner() { yield "a"; yield "b"; }
function* outer() { yield* inner(); yield "c"; }
console.log([...outer()]);
Output
[ 'a', 'b', 'c' ]
Notes
- `yield` is only valid inside a generator function (`function*`).
- `yield*` delegates iteration to another iterable or generator.
- The value of a `yield` expression is whatever is passed to `next()`.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 39 |
| firefox | 26 |
| safari | 10 |
| edge | 13 |
| node | 4.0 |