liveBook · Manning

Yield

As explained in Secrets of the JavaScript Ninja, Third Edition

A yield expression is an expression inside a generator function that suspends execution and evaluates to a value supplied when the generator resumes.

Inside a generator function, `yield` suspends execution and produces a value. Calling `next()` resumes the function where it paused; unlike `await`, `yield` does not pause the JavaScript thread. A value passed to `next()` becomes the result of the paused `yield` expression. section 8.3.2

Two-way exchange

A generator can yield its current value, then use the next value sent in to update its state. Repeated calls to `next()` drive the exchange. section 8.3.2

Listing 8.12 A generator with two-way yield
function* multiplier(): Generator<number, unknown, number> { #A
  let number  = 1;
  while (true) {
    const multiplier = yield number; #B
    number *= multiplier; #B
  }
}

const multiplierGenerator = multiplier();
console.assert(multiplierGenerator.next().value === 1);
console.assert(multiplierGenerator.next(5).value === 5);
console.assert(multiplierGenerator.next(4).value === 20);

Follow a multiplier generator as values are yielded and passed back through `next()`. section 8.3.2

A `yield` result has `done: false`; a generator’s return produces `done: true`. Use `yield*` to delegate yielding to another generator. section 8.3.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains suspension, resumption, iterator results, and values passed through next().
Examples
Uses an infinitely iterable random-number generator, a two-way multiplier, and delegation to another generator.
What you can do after
Apply yield with next() to pause and resume a generator while sending values in both directions.
How it connects
Connects yield to generator functions, iterables, next(), return, yield*, and await.

Also explained in

Compare how 11 books explain yield →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.