Sub topic 8
Generator Functions with function* and yield
In the previous chapters you built iterators by hand. You wrote a next() method, tracked state in closure variables, and returned { value, done } objects yourself. That approach works, but most of the code is bookkeeping. A generator function is a special kind of function that produces an iterator for you. You write ordinary-looking code, and each yield statement hands one value to whoever is iterating.
This chapter assumes you are comfortable with functions and closures, classes and methods, and the iterator protocol from earlier chapters (next() and { value, done }). It covers the syntax, what calling a generator gives you, and how yield and return map onto iterator results. The next chapter goes deeper into how a generator pauses and resumes.
The syntax: function* and yield
A generator function is declared with an asterisk after the function keyword. Inside it, the yield keyword produces a value and pauses the function.
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)Here is what each part does:
count()does not run the body. It returns a generator object, an object that follows the iterator protocol.- Each
g.next()runs the body until the nextyield, then pauses. The yielded value goes into{ value, done: false }. return 3finishes the generator. The returned value goes into{ value: 3, done: true }.- After the generator finishes, every further
next()call returns{ value: undefined, done: true }. - Spread, like
for...of, stops as soon as it seesdone: true, so it never includes the3.
If the body runs off the end with no return, the final result is { value: undefined, done: true }, the same as an ordinary function returning undefined.
Where the asterisk can go
The asterisk works in every place you can define a normal function except an arrow function. Generator arrow functions do not exist.
// Declaration
function* letters() {
yield 'a';
yield 'b';
}
// Expression
const digits = function* () {
yield 0;
yield 1;
};
// Object method shorthand
const obj = {
*pair() {
yield 'left';
yield 'right';
}
};
// Class method (instance and static)
class Colors {
*primary() {
yield 'red';
yield 'green';
yield 'blue';
}
static *grays() {
yield 'black';
yield 'white';
}
}
console.log([...letters()]); // [ 'a', 'b' ]
console.log([...digits()]); // [ 0, 1 ]
console.log([...obj.pair()]); // [ 'left', 'right' ]
console.log([...new Colors().primary()]); // [ 'red', 'green', 'blue' ]
console.log([...Colors.grays()]); // [ 'black', 'white' ]Whitespace around the asterisk does not matter: function* f, function *f, and function*f are all valid. Most style guides put it next to function, as in function*, because it modifies the kind of function, not the name. In methods the asterisk goes before the name (*pair()), and that includes computed names such as *[Symbol.iterator](). Chapter 10 covers that case.
The generator object is both iterator and iterable
A generator object has next(), return(), and throw() methods, so it is an iterator. It also has a [Symbol.iterator]() method that returns the object itself, so it is iterable. That is why you can pass the result of a generator call straight to for...of, spread, destructuring, or Array.from.
function* letters() {
yield 'x';
yield 'y';
yield 'z';
}
const g = letters();
console.log(g[Symbol.iterator]() === g); // true
console.log(Object.prototype.toString.call(g)); // [object Generator]
for (const ch of letters()) {
console.log(ch); // x, y, z
}
const [first, second] = letters();
console.log(first, second); // x y
console.log(Array.from(letters(), ch => ch.toUpperCase())); // [ 'X', 'Y', 'Z' ]Each call to a generator function creates a new, independent generator object with its own position in the body. Two calls never share progress:
function* count() {
yield 1;
yield 2;
}
const a = count();
const b = count();
console.log(a.next().value); // 1
console.log(a.next().value); // 2
console.log(b.next().value); // 1 (b has its own state)yield is an expression
yield produces a value, and it is also an expression that evaluates to something when the generator resumes. With a plain next() call that something is undefined. Chapter 12 shows how next(value) supplies it. For now, two practical rules matter.
First, yield has very low precedence, about the same as assignment. yield a + b yields the sum. When you use yield inside a larger expression, wrap it in parentheses: 'got ' + (yield 1).
Second, yield works only directly inside the generator function's own body. It does not reach into nested functions, including callbacks.
function* doubled(items) {
// items.forEach(x => { yield x * 2; }); // SyntaxError: the arrow is not a generator
for (const x of items) {
yield x * 2; // fine: the loop is part of the generator's own body
}
}
console.log([...doubled([1, 2, 3])]); // [ 2, 4, 6 ]Loops, if statements, switch, try blocks, and plain blocks all keep you inside the generator body, so yield works in all of them. A callback passed to forEach, map, or setTimeout is a separate function, so yield inside it is a syntax error. Replace those callbacks with a for...of loop.
Comparing a hand-written iterator with a generator
Here is the same three-value sequence written both ways:
function makeIterator() {
let step = 0;
return {
next() {
step++;
if (step === 1) return { value: 'a', done: false };
if (step === 2) return { value: 'b', done: false };
if (step === 3) return { value: 'c', done: false };
return { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
}
};
}
function* makeGenerator() {
yield 'a';
yield 'b';
yield 'c';
}
console.log([...makeIterator()]); // [ 'a', 'b', 'c' ]
console.log([...makeGenerator()]); // [ 'a', 'b', 'c' ]| Concern | Hand-written iterator | Generator |
|---|---|---|
| Tracking position | Manual counter or state variable | Implicit: the paused location in the body |
| Building result objects | You write `{ value, done }` | Created for you by `yield` and `return` |
| Being iterable | You add `[Symbol.iterator]()` | Built in |
| `return()` and `throw()` | Optional, you write them | Always present |
| Behavior after finishing | You must keep returning `done: true` | Guaranteed |
Common errors
- Forgetting the asterisk. With
function count() { yield 1; }, the code fails with a SyntaxError in strict mode and modules. In sloppy-mode scripts,yieldcan even be read as an identifier. - Expecting the body to run on call.
count()alone runs nothing, so anyconsole.logat the top of the body stays silent until the firstnext(). - Expecting
for...ofto see the return value. Values sent withreturnarrive withdone: true, and loops discard them. If consumers need a value,yieldit. - Using
yieldinside a callback. Use a loop that is part of the generator's own body. - Reusing a finished generator. After it completes, it stays done. Call the generator function again to get a fresh one.
Exercise
Predict every line this code logs, in order. function* steps() { console.log('start'); yield 'one'; console.log('middle'); yield 'two'; console.log('end'); return 'three'; } const s = steps(); console.log('created'); console.log(s.next()); console.log(s.next()); console.log(s.next()); console.log([...steps()]);
Show answer
'created' comes first because calling steps() does not run the body. Then 'start' and { value: 'one', done: false }. Then 'middle' and { value: 'two', done: false }. Then 'end' and { value: 'three', done: true }. The spread creates a new generator and logs 'start', 'middle', 'end' as it runs. Last comes [ 'one', 'two' ], because spread ignores the 'three' that arrives with done: true.
Exercise
Write a generator function evens(limit) that yields every even number from 0 up to, but not including, limit. Then use it to log [0, 2, 4, 6, 8] with spread.
Show answer
function* evens(limit) { for (let n = 0; n < limit; n += 2) { yield n; } } and then console.log([...evens(10)]); which prints [ 0, 2, 4, 6, 8 ]. The loop is part of the generator's own body, so yield is allowed there.
Exercise
Why does const g = function* () { [1, 2].forEach(x => { yield x; }); }; fail, and how do you fix it?
Show answer
The arrow function passed to forEach is a separate, non-generator function, so yield inside it is a SyntaxError. Replace forEach with for (const x of [1, 2]) { yield x; } so the yield sits directly in the generator's body.