What if a function could hand back a value without losing its place? A generator does just that. Calling a generator function, written with `function*`, creates a new generator object. The function body waits until you call the object's `next()` method. section 18.0 section 18.1 section 18.2
Start, pause, resume
`function* letters() { console.log('Started'); const reply = yield 'a'; console.log(reply); yield 'b'; } const gen = letters(); // Nothing logged yet. gen.next(); // Logs Started; { value: 'a', done: false } gen.next('hello'); // Logs hello; { value: 'b', done: false } gen.next(); // { value: undefined, done: true }` Each `yield` pauses execution and sends a value out. On the following `next(value)`, that argument becomes the result of the paused `yield` expression. An argument to the *first* `next()` is ignored; use a generator-function parameter for an initial value. Once the function finishes, `done` becomes `true`. A final `return` can supply a value in that result; otherwise its value is `undefined`. section 18.1 section 18.2
This makes a generator useful for values produced on request. In `function* count() { let i = 0; while (true) yield i++; }`, each call to `count().next()` would start a *new* generator; keep one object instead: `const numbers = count();` then call `numbers.next()` repeatedly to get 0, 1, 2, and so on. The endless loop pauses at every yield rather than producing an endless array at once. section 18.1 section 18.3
A generator is also both an iterator and an iterable. For a finite sequence, `function* primes() { yield 2; yield 3; yield 5; }`, the expression `[...primes()]` produces `[2, 3, 5]`. A generator function can also serve as an object's `[Symbol.iterator]` method. section 23.4
Pausing can coordinate more than lists. A simulation can request an object with `next()`, then pass previous results into the generator on its next call. A timed helper can call `next()` at intervals, making each `yield` a visible pause. Try writing a generator for odd numbers and requesting just its first few values. section 19.1 section 26.2 section 18.3











