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

What Makes a Sequence Lazy?

Understand lazy evaluation: computing values on-demand rather than upfront, enabling infinite sequences and better performance.

What Makes a Sequence Lazy?

You'll learn: How lazy evaluation computes values only when needed, enabling efficient handling of large or infinite sequences.

The Core Idea

Imagine a recipe book that doesn't print all its pages until you turn to them. That's lazy evaluation—instead of computing all values upfront and storing them in memory, a lazy sequence generates each value only when requested.

In JavaScript, generators are naturally lazy. When you call a generator function, it doesn't execute its body immediately. It waits. Only when you call next() does it run until the next yield, produce a value, and pause again.

Eager vs Lazy

Eager evaluation (like arrays):

// All values computed immediately
const eagerNumbers = [1, 2, 3, 4, 5]; // All 5 exist in memory

Lazy evaluation (generators):

function* lazyNumbers() {
  yield 1;
  yield 2;
  yield 3;
  // Values produced one at a time, only when next() is called
}

const gen = lazyNumbers(); // Nothing computed yet!
gen.next(); // Now it computes: { value: 1, done: false }

Why Lazy Matters

Infinite sequences become possible:

function* infiniteCounter() {
  let n = 0;
  while (true) yield n++;
}
// This would crash if eager—but lazy, it's perfectly safe

Performance gains: Process huge datasets without loading everything into memory. Compute only what you actually use.

On-demand computation: Expensive operations run only when values are needed, not before.

Key Takeaway: Lazy sequences compute values on-demand rather than upfront, making generators memory-efficient and capable of representing infinite or very large datasets without overwhelming your program.