Course contentsShow
← JavaScript
Lesson 2049 of 2,72342. Iteration Protocols Deep DiveFree lesson

What Makes an Iterator Lazy

Understanding deferred computation: why lazy iterators produce values on-demand rather than upfront.

What Makes an Iterator Lazy

You'll learn why lazy iterators produce values only when requested, not all at once.

Understanding Deferred Computation

An iterator is lazy because it doesn't compute or generate its values until you explicitly ask for them by calling next(). This is fundamentally different from creating an array upfront, where all values exist in memory immediately.

Think of it like a vending machine: the snacks don't appear until you press a button. A lazy iterator works the same way—each value is produced on-demand when next() is called, not before.

Why This Matters

When you write a generator function or create a custom iterator, the code inside doesn't run until consumption begins:

function* lazyNumbers() {
  console.log('Starting...');
  yield 1;
  console.log('After first yield');
  yield 2;
  console.log('After second yield');
  yield 3;
}

const iterator = lazyNumbers(); // Nothing logged yet!
iterator.next(); // Logs "Starting...", returns {value: 1, done: false}
iterator.next(); // Logs "After first yield", returns {value: 2, done: false}

Notice how "Starting..." didn't appear until the first next() call. The function paused at each yield and only continued when explicitly asked.

Benefits of Laziness

Lazy iterators conserve memory (don't store all values), enable working with infinite sequences, and avoid unnecessary computation for values you might never need. If you only consume the first three items from a generator that could produce millions, only three values ever get computed.

Key Takeaway: Lazy iterators produce values on-demand through next() calls rather than computing everything upfront, enabling efficient, memory-conscious iteration.