Sub topic 10
Writing Iterables with Generators
This chapter assumes you have read the earlier chapters. You should know the iterable and iterator protocols, have built a custom iterable by hand, and understand how a generator pauses at yield and resumes on next().
The idea
A generator object already follows both protocols. It has a next() method that returns { value, done }. Its [Symbol.iterator]() method returns the generator object itself. So if you write [Symbol.iterator] as a generator method, calling it returns a correct iterator, and you never build that iterator object yourself.
Rewriting Range
The hand-built Range from earlier needed an explicit next(), a current variable kept in a closure, a done flag, and a [Symbol.iterator] method that returned this. With a generator method, all of that goes away:
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 method name makes the method a generator. The loop variable i now holds the iteration state, and that state stays alive because the generator is suspended rather than finished. When the loop ends, the generator completes and reports done: true for you.
Fresh iterators on every pass
Each call to a generator function creates a new generator object. Every for...of, spread, or destructuring calls [Symbol.iterator]() again, so each pass gets its own independent state:
const r = new Range(0, 3);
console.log([...r], [...r]); // [ 0, 1, 2 ] [ 0, 1, 2 ]This makes Range reusable, the way an array is. A single generator object behaves differently, because it can be used only once.
Object literals and data structures
The same syntax works in object literals. It is especially useful for structures whose traversal would be awkward to write by hand, such as a linked list:
const list = {
head: { value: 'a', next: { value: 'b', next: null } },
*[Symbol.iterator]() {
for (let node = this.head; node; node = node.next) {
yield node.value;
}
}
};
for (const v of list) console.log(v); // a, then bCommon errors
| Mistake | Result |
|---|---|
| Forgetting the `*` | `yield` causes a SyntaxError |
| Using `return value` to emit the last item | `for...of` and spread skip it |
| Storing one generator object and returning it from `[Symbol.iterator]` every time | The second pass is empty |
Exercise
Write a class Countdown whose constructor takes n, so that [...new Countdown(3)] gives [3, 2, 1] and can be spread more than once with the same result.
Show answer
class Countdown { constructor(n) { this.n = n; } *[Symbol.iterator]() { for (let i = this.n; i > 0; i--) yield i; } } Each spread calls the generator method again, so each pass starts from n.
Exercise
Why does [...list] above work even though the object literal never defines a next() method?
Show answer
Calling list[Symbol.iterator]() runs a generator method, and that returns a generator object. The generator object supplies next() and follows the iterator protocol, so the iterable itself never needs a next().