Sub topic 10
Writing Iterables with Generators
This chapter assumes you have read the earlier chapters on the iterable and iterator protocols, on building a custom iterable by hand, and on how generators pause and resume. You should also be comfortable with classes, methods, and computed property names such as [Symbol.iterator].
Earlier you built a Range class by hand. Its Symbol.iterator method returned an object with a next() method, a closure holding the current position, an explicit done flag, and a [Symbol.iterator]() { return this; } method so the iterator was itself iterable. That design works, but most of it is boilerplate. A generator function produces an object that already satisfies both protocols, so it is the usual way to write Symbol.iterator.
From hand-built iterator to generator method
Here is Range again, with the iterator method written as a generator:
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) {
yield i;
}
}
}
console.log([...new Range(1, 4)]); // [ 1, 2, 3 ]The * before the computed name [Symbol.iterator] makes the method a generator method. Calling it does not run the loop. It returns a new generator object, and that object is an iterator. Each yield i becomes one { value: i, done: false } result. When the loop ends and the function body finishes, the generator reports { value: undefined, done: true }.
Compare what each version has to manage:
| Concern | Hand-built iterator | Generator method |
|---|---|---|
| Result objects | You build `{ value, done }` yourself | Created by `yield` and by completion |
| Position state | Closure variables you update | Ordinary local variables like `i` |
| Finishing | You return `{ done: true }` and must keep returning it | Automatic when the body ends |
| Iterator is iterable | You add `[Symbol.iterator]() { return this; }` | Built into generator objects |
| Early exit | You write an optional `return()` | `return()` exists and runs `finally` blocks |
The last row matters more than it looks. A hand-written iterator that forgets return() gets no cleanup on break. A generator always has return(), and a later chapter shows how try...finally hooks into it.
What happens when for...of runs
The diagram shows how a for...of loop over a Range meets the generator.
Each call to [Symbol.iterator]() creates a separate generator with its own i. That gives you the behaviour arrays have: the same Range can be spread, destructured, and looped over as many times as you like, and two loops over it at once do not interfere.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) {
yield i;
}
}
}
const r = new Range(0, 2);
for (const a of r) {
for (const b of r) {
console.log(a, b); // 0 0, 0 1, 1 0, 1 1
}
}Generator objects are iterable themselves
A generator object has a [Symbol.iterator] method that returns the object itself. That is why you can pass a generator call directly to for...of or spread:
function* letters() {
yield 'a';
yield 'b';
}
const g = letters();
console.log(g[Symbol.iterator]() === g); // true
console.log([...g]); // [ 'a', 'b' ]This gives you two shapes to choose from:
- A reusable iterable: an object whose
[Symbol.iterator]is a generator method. Every iteration starts fresh. - A one-shot iterator: the generator object returned by calling a generator function. Once it is consumed, it stays finished.
Collections should almost always be the first kind. A function that produces a stream of values, such as reading lines or generating IDs, is often fine as the second.
Object literals and plain functions
You do not need a class. Object literals accept the same generator method syntax:
const weekdays = {
names: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
*[Symbol.iterator]() {
for (const name of this.names) {
yield name.toUpperCase();
}
}
};
console.log([...weekdays]); // [ 'MON', 'TUE', 'WED', 'THU', 'FRI' ]Inside a generator method, this is the object the method was called on, as with any ordinary method. for...of calls weekdays[Symbol.iterator](), so this is weekdays.
There is no generator arrow function. *() => {} is a syntax error. If you assign a generator to a property, use function*:
const evens = {};
evens[Symbol.iterator] = function* () {
for (let n = 0; n <= 6; n += 2) yield n;
};
console.log(Array.from(evens)); // [ 0, 2, 4, 6 ]Iterating internal structure: a linked list
Generators are especially useful when the data is not stored in an array. The generator walks the structure with ordinary control flow and yields as it goes. Built-in collections like Map also offer several views, keys(), values(), and entries(), and you can copy that design with extra generator methods:
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
push(value) {
const node = { value, next: null };
if (this.head === null) {
this.head = node;
} else {
let cur = this.head;
while (cur.next !== null) cur = cur.next;
cur.next = node;
}
this.size++;
return this;
}
*values() {
for (let node = this.head; node !== null; node = node.next) {
yield node.value;
}
}
*entries() {
let index = 0;
for (const value of this.values()) {
yield [index++, value];
}
}
[Symbol.iterator]() {
return this.values();
}
}
const list = new LinkedList().push('x').push('y').push('z');
console.log([...list]); // [ 'x', 'y', 'z' ]
for (const [i, v] of list.entries()) {
console.log(i, v); // 0 x, 1 y, 2 z
}The [Symbol.iterator] here is a plain method that returns this.values(). That is valid because it returns a fresh iterator on every call, which is all the iterable protocol requires. This matches the built-ins: Map.prototype[Symbol.iterator] is the same function as Map.prototype.entries.
Recursive structures such as trees are also natural to walk with generators. They usually need yield* to pass along values from recursive calls, which the next chapter covers.
Edge cases to keep in mind
- Mutation during iteration. The generator reads the structure live, when it resumes. If you
pushonto theLinkedListmid-loop, the loop will see the new node once it gets there. Arrays behave the same way. If you need a stable snapshot, copy the data before you start yielding. - Errors surface lazily. A check inside the generator body, such as throwing when
start > end, does not run when[Symbol.iterator]()is called. It runs on the firstnext(). Validate arguments in the constructor if you want errors to appear early. - The return value is ignored. A
return 'done'inside the generator method is not seen byfor...of, spread, orArray.from, because it arrives withdone: true. Put everything consumers should see inyield. - Infinite sources are allowed. A generator method can loop forever. Consumers that read everything, like spread, will then hang. A later chapter covers safe ways to consume them.
Exercise
Write a class Countdown whose constructor takes n, and whose instances are reusable iterables that yield n, n - 1, ..., 1. Then explain why [...c] works twice on the same instance c.
Show answer
class Countdown { constructor(n) { this.n = n; } *[Symbol.iterator]() { for (let i = this.n; i > 0; i--) yield i; } }. With const c = new Countdown(3), [...c] gives [ 3, 2, 1 ] both times, because each spread calls c[Symbol.iterator](), and calling a generator method creates a new generator object with its own loop variable i.
Exercise
A developer writes class Bag { constructor(items) { this.items = items; this.it = this.gen(); } gen() { yield this.items; } [Symbol.iterator]() { return this.it; } }. The first for...of over a Bag works but the second prints nothing. Why, and what is the one-line fix?
Show answer
The constructor creates a single generator and Symbol.iterator returns that same object every time. After the first loop, the generator is finished, so later loops get done: true immediately. The fix is to create a new generator per call: [Symbol.iterator]() { return this.gen(); } (or make Symbol.iterator itself the generator method).
Exercise
Given const obj = { *[Symbol.iterator]() { console.log('start'); yield 1; } }; const it = obj[Symbol.iterator](); — is 'start' logged at this point? When is it logged?
Show answer
No. Calling the generator method only creates the generator object; the body has not started. 'start' is logged on the first it.next() call (or when a consumer such as for...of or spread requests the first value).