AdvancedLesson 15 of 16
Iterators & Generators – JavaScript
Making your own collections iterable and producing values lazily.
Everything that for...of can iterate over follows the iterator protocol: an object with [Symbol.iterator]() returns an iterator whose next() returns { value, done }.
const it = [10, 20][Symbol.iterator]();
console.log(it.next(), it.next(), it.next());
// { value: 10, done: false } { value: 20, done: false } { value: undefined, done: true }Generator functions (function*) make writing iterators convenient: yield delivers a value and pauses the function – ideal for large or infinite sequences.
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function* nimm(iterable, n) {
let i = 0;
for (const x of iterable) {
if (i++ >= n) return;
yield x;
}
}
console.log([...nimm(fibonacci(), 10)]); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]With *[Symbol.iterator]() you make your own classes iterable – and therefore compatible with for...of, spread and destructuring:
class Bereich {
constructor(von, bis) {
this.von = von;
this.bis = bis;
}
*[Symbol.iterator]() {
for (let i = this.von; i <= this.bis; i++) yield i;
}
}
const b = new Bereich(1, 5);
console.log([...b], Math.max(...b));
const [ersteZahl, zweiteZahl] = b;
console.log(ersteZahl, zweiteZahl); // 1 2Map, Set and strings are iterable too. Handy: Object.fromEntries and Map convert between objects and pairs.
const m = new Map([["a", 1], ["b", 2]]);
for (const [k, v] of m) console.log(k, v);
console.log(Object.fromEntries(m)); // { a: 1, b: 2 }
console.log(new Map(Object.entries({ x: 1 })));TipNewer engines (current browsers, Node 22+) have "iterator helpers":
iterator.map(...).filter(...).take(5).toArray() processes streams lazily, without intermediate arrays. For async data streams you use async function* and for await...of.