Iterators and Generators
Values on demand.
For of works on arrays, strings, sets, and maps. That's because they're all iterable. They know how to give out their values one at a time. With a generator function, you can make your own iterable, that produces values only when they're asked for.

- for of works on many things
- They're iterable
- Make your own with generators
function*
A generator is written with function star. Each yield hands out one value, and pauses the function until the next value is wanted. Range yields numbers from start to end. Because it's iterable, we can loop over it, or spread it into an array, or call next by hand. Run it.
function* range(start, end, step = 1) {
for (let i = start; i < end; i += step) {
yield i;
}
}
for (const n of range(0, 3)) console.log("n =", n);
console.log([...range(0, 20, 5)]);
const it = range(10, 12);
console.log(it.next().value, it.next().value, it.next().done);n = 0 n = 1 n = 2 [ 0, 5, 10, 15 ] 10 11 true
Endless sequences
A generator can even go on forever, because it only does work when asked. Fibonacci yields the sequence with no end. Take pulls just the first few values, and stops. An array of every Fibonacci number would never finish, but this is instant. Run it.
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function take(n, iterable) {
const out = [];
for (const x of iterable) { if (out.length === n) break; out.push(x); }
return out;
}
console.log(take(10, fibonacci()));[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
Summary
Generators use function star and yield to produce values on demand, and they work with for of and spread. Next, a command line notes tool in Node.
Key takeaways- function*
- yield pauses
- Lazy, even endless