Building an Infinite Range Generator
What you'll learn: How to create a generator that produces numbers endlessly without consuming memory upfront.
The Core Idea
An infinite range generator is a function that can yield numbers forever—or at least until you stop asking for them. Unlike an array that must store all its values in memory, a generator computes each number only when requested. This "lazy" approach means you can work with theoretically infinite sequences without running out of memory.
Think of it like a ticket dispenser at a deli counter: it doesn't print all possible numbers at once. It just generates the next number whenever someone presses the button.
Creating an Infinite Range
Here's how to build a generator that counts upward indefinitely:
function* infiniteRange(start = 0, step = 1) {
let current = start;
while (true) {
yield current;
current += step;
}
}
const counter = infiniteRange(1, 2);
console.log(counter.next().value); // 1
console.log(counter.next().value); // 3
console.log(counter.next().value); // 5
// Could continue forever...
The while (true) loop never ends, but that's okay—the generator pauses at each yield. You control when to ask for the next value. The computation doesn't happen until you call next().
Practical Use
You can safely take just what you need from an infinite sequence:
function* count() {
let n = 0;
while (true) yield n++;
}
// Take only the first 5 numbers
const firstFive = [];
const numbers = count();
for (let i = 0; i < 5; i++) {
firstFive.push(numbers.next().value);
}
console.log(firstFive); // [0, 1, 2, 3, 4]
Key Takeaway: Infinite range generators demonstrate the power of lazy evaluation—they produce values on demand without memory overhead, letting you work with endless sequences safely by controlling when to stop consuming values.