JavaScript › Iterators & Generators

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

Intermediate

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.

Common follow-ups: How would you take just the first N values from an infinite generator?