Building an Infinite Range Iterator
You'll learn how to create a custom iterator that generates numbers endlessly, demonstrating the power of lazy evaluation.
The Concept
An infinite range iterator is a never-ending sequence of numbers. Unlike an array that must hold all its values in memory, an infinite iterator produces values on demand, one at a time, and never stops. This is possible because iterators are lazy—they only compute the next value when you explicitly ask for it.
Think of it like counting out loud: you don't need to write down every number from 1 to infinity before you start. You just say the next number each time someone asks.
Creating an Infinite Range
Here's a simple infinite range iterator that starts at a given number and increments forever:
function infiniteRange(start = 0, step = 1) {
return {
[Symbol.iterator]() {
let current = start;
return {
next() {
const value = current;
current += step;
return { value, done: false };
}
};
}
};
}
// Use it (carefully!)
const numbers = infiniteRange(1);
const iterator = numbers[Symbol.iterator]();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
// ... goes on forever
Notice that done is always false—the iterator never finishes. Because it's lazy, this doesn't freeze your program. Memory stays constant because we only track current, not an infinite list.
You can safely use this with manual .next() calls or break conditions, but never with patterns that try to consume everything at once.
Key Takeaway: Infinite iterators rely on laziness to generate endless sequences without memory overflow, producing each value only when requested and never signaling completion.