JavaScript › Iterators & Generators
How do you implement an infinite sequence using a generator, and why is this safe?
IntermediateAnswer
A generator can loop forever internally (e.g. while (true)) because it only computes and yields one value at a time when next() is called — nothing is precomputed, so it never actually tries to build an infinite array in memory.
function* naturalNumbers() {
let n = 1;
while (true) {
yield n++;
}
}
const gen = naturalNumbers();
gen.next().value; // 1
gen.next().value; // 2Real-world example Generating an ID sequence or lazily producing values for an infinite scroll feed, only as needed.