Course contentsShow
← JavaScript
Lesson 1120 of 2,72325. Iterators and GeneratorsFree lesson

Generators as Lazy Sequences

See how generator functions naturally create lazy sequences that pause execution and resume when values are needed.

Generators as Lazy Sequences

You'll learn how generator functions create sequences that only compute values on-demand, saving memory and processing time.

What Is a Lazy Sequence?

A lazy sequence is one that doesn't compute all its values upfront. Instead, it waits until each value is actually requested before generating it. Think of it like a chef who only cooks dishes when customers order them, rather than preparing hundreds of meals in advance that might go to waste.

How Generators Enable Laziness

Generator functions naturally create lazy sequences because they pause at each yield statement. The generator only computes the next value when you call next() on it. This happens automatically when you use for...of or spread operators, but the key point is: no value is calculated until it's needed.

function* countUpTo(max) {
  console.log('Generator started');
  let count = 1;
  while (count <= max) {
    console.log(`About to yield ${count}`);
    yield count;
    count++;
  }
  console.log('Generator done');
}

const counter = countUpTo(3);
// Nothing logged yet! Generator hasn't started.

console.log(counter.next().value); // Logs: 'Generator started', 'About to yield 1', then 1
console.log(counter.next().value); // Logs: 'About to yield 2', then 2

Notice how the generator only runs code when next() is called. Each value is computed just-in-time.

Why This Matters

Without generators, creating a sequence of a million numbers would require storing all million in memory at once. With generators, you compute and hold only one value at a time. You can even create infinite sequences because you never need to generate "all" values.

Key Takeaway: Generators create lazy sequences by pausing execution at each yield and only computing the next value when explicitly requested, making them memory-efficient and capable of representing infinite collections.