Advertisement
Intermediate JavaScript, Iterators & Generators

How do you implement an infinite sequence using a generator, and why is this safe?

Short answer

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.

Save JavaScript mock interview
Advertisement
AModel answer
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; // 2
Real-world example
Generating an ID sequence or lazily producing values for an infinite scroll feed, only as needed.
Likely follow-ups
  • How would you take just the first N values from an infinite generator?
Related topics