Advanced JavaScript PatternsLesson 6.3
Iterators and generators in JavaScript explained
iterator protocol, Symbol.iterator, custom iterables, generator functions, yield keyword, Generator object, infinite sequences, generator-based async, lazy evaluation
The Iterator Protocol
An iterator is any object with a next() method that returns { value, done }. An iterable is any object with a [Symbol.iterator] method that returns an iterator. Arrays, strings, Maps, and Sets are all built-in iterables โ that's why for-of works on them.
Custom Iterable
const range = {
from: 1, to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
}
};
}
};
for (const n of range) console.log(n); // 1 2 3 4 5
Generators โ Simpler Iterators
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i; // pauses here, resumes on next .next() call
}
}
const gen = range(1, 3);
gen.next(); // { value: 1, done: false }
gen.next(); // { value: 2, done: false }
gen.next(); // { value: 3, done: false }
gen.next(); // { value: undefined, done: true }
// or use spread
[...range(1, 5)] // [1, 2, 3, 4, 5]
Lazy Evaluation
Generators produce values on demand โ useful for infinite sequences or large datasets where you don't want to compute everything upfront.
