Sub topic 8
Generator Functions with function* and yield
This chapter assumes you already know the iterator protocol from earlier chapters: an iterator has a next() method that returns { value, done }. It also assumes you are comfortable with functions and object methods.
Building an iterator by hand takes some work. You have to write a next() method, keep its state in a closure, and set done correctly. A generator function asks the engine to do all of that for you.
The Syntax
A generator function is a function declared with function*. Inside it, the yield keyword hands a value to whoever is iterating and pauses the function at that point.
function* count() {
yield 1;
yield 2;
return 3;
}
const g = count(); // the body has not run yet
console.log(g.next()); // { value: 1, done: false }
console.log(g.next()); // { value: 2, done: false }
console.log(g.next()); // { value: 3, done: true }
console.log(g.next()); // { value: undefined, done: true }
console.log([...count()]); // [ 1, 2 ] (the return value is not included)Calling count() does not run any of its code. It returns a generator object, and that object is an iterator. Each call to next() runs the body up to the next yield, then pauses. When the body reaches return, or simply ends, the result has done: true.
What Each Statement Produces
| Statement in the body | Result of `next()` |
|---|---|
| `yield x` | `{ value: x, done: false }` |
| `return x` | `{ value: x, done: true }` |
| End of body with no `return` | `{ value: undefined, done: true }` |
| Any call after the generator has finished | `{ value: undefined, done: true }` |
Where You Can Write Generators
You can write a generator as a declaration, as an expression, or as a method:
function* a() { yield 'declaration'; }
const b = function* () { yield 'expression'; };
const obj = {
*c() { yield 'method'; }
};
console.log([...a(), ...b(), ...obj.c()]);
// [ 'declaration', 'expression', 'method' ]Arrow functions have no generator form. yield is also valid only directly inside a generator body. If you use it inside a nested regular function or callback, such as one passed to forEach, you get a syntax error.
Common Errors
- If you expect
count()to log or compute something right away, nothing happens. The body runs only when you callnext(). - If you forget the
*, the function is an ordinary function, and anyyieldinside it is a syntax error. - If you put a final result in
return,for...ofdrops it without any warning.
The next chapter looks at this pause-and-resume behavior in more detail.
Exercise
Given function* g() { console.log('start'); yield 'x'; console.log('end'); }, what is logged by const it = g(); it.next(); it.next(); and what does the second next() return?
Show answer
Calling g() logs nothing. The first next() logs 'start' and returns { value: 'x', done: false }. The second next() logs 'end' and returns { value: undefined, done: true }, because the body ended without a return statement.
Exercise
What does console.log([...(function* () { yield 'a'; return 'b'; })()]) print, and why?
Show answer
It prints [ 'a' ]. Spread stops when the result has done: true, and the returned 'b' arrives in that same result, so spread never collects it.