What if a function could produce a value without finishing? Inside a generator function, `yield` sends a value out and pauses execution. Unlike `return`, it leaves the remaining code ready to run when the generator resumes. section 18.1
Pause, then continue
function* letters() { yield 'a'; yield 'b'; } const gen = letters(); gen.next(); // { value: 'a', done: false } gen.next(); // { value: 'b', done: false } gen.next(); // { value: undefined, done: true } Calling `letters()` creates a generator object but does not run its body. The first `next()` starts it and stops at the first `yield`; each later call resumes from the pause. When no code remains, `done` becomes `true`. section 18.2 section 18.1
`yield` is also an expression, so information can travel back in. In `const reply = yield 'question';`, the call that reaches `yield` produces `'question'`. The *following* `next('answer')` resumes the function and assigns `'answer'` to `reply`. An argument to the very first `next()` is not received by a `yield`; use a function parameter for an initial value. section 18.1 section 18.2
Produce only what is requested
function* numbers() { let i = 0; while (true) yield i++; } const list = numbers(); list.next().value; // 0 list.next().value; // 1 The endless loop does not run endlessly at once: each `yield` pauses it. Only requested values are produced. The same pattern can generate Fibonacci numbers or odd numbers. section 18.3
A pause can do more than build a sequence:
- A simulation can receive a generated object, then pass its results into the generator through the next `next()` call so later objects can adapt. section 19.1
- A timed runner can call `next()` at intervals. Placing `yield` in a CPU turn then marks where execution should wait before continuing. section 26.2
- A generator can yield key–value pairs for `for..of`, avoiding a manually written iterator’s `next()` method. section 23.4
Try writing a generator that yields successive dates. Check that its first `next()` gives the starting day and each subsequent call gives the next day. section 18.4









