yield
In JavaScript, the yield keyword pauses a generator function and hands a value to the code iterating it, then resumes from the same spot on the next request. It only works directly inside a generator body, which function* defines with the function keyword.
Each call to the generator’s .next() method runs the body up to the next yield and returns an object such as { value: 1, done: false }. The argument passed to .next() becomes the value of the paused yield expression. A bare yield produces undefined.
The yield* form delegates to another iterable, such as an array or another generator, and yields each of its values in turn. Inside an async generator, yield* also accepts async iterables.
The word is reserved in strict mode code and inside generator bodies. Sloppy-mode scripts can still use it as an identifier. Generators and yield were added in ES2015.
JavaScript yield Keyword Syntax
The yield keyword has two forms:
yield [<expression>]
yield* <iterable>
JavaScript yield Keyword Examples
A generator function pauses at each yield and resumes when .next() asks for another value:
> function* createIds(prefix) {
… let id = 1;
… while (true) {
… const reset = yield `${prefix}-${id}`;
… id = reset ? 1 : id + 1;
… }
… }
undefined
> const ids = createIds("user");
undefined
> ids.next()
{ value: 'user-1', done: false }
> ids.next().value
'user-2'
> ids.next(true).value
'user-1'
The loop never ends, but the generator only runs when .next() asks for a value. Passing true makes the paused yield evaluate to true, which resets the counter.
The yield* form hands iteration over to another iterable until it’s exhausted:
> function* letters() {
… yield "a";
… yield* ["b", "c"];
… }
undefined
> [...letters()]
[ 'a', 'b', 'c' ]
> const yield = "a sloppy-mode name";
undefined
The last line works only because the REPL runs sloppy-mode code outside any generator. In a module or a generator body, it’s a SyntaxError.
JavaScript yield Keyword Use Cases
- Producing sequences of values lazily, one at a time
- Generating infinite sequences such as IDs or counters
- Making custom objects iterable with a generator method
- Flattening nested data by delegating with
yield*
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 6, 2026