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

Lazy Iterators and For-Of

How for-of interacts with infinite iterators and techniques to safely break out of loops.

Lazy Iterators and For-Of

What you'll learn: How for-of consumes lazy iterators and when you need to manually break out of infinite loops.


How For-Of Interacts with Lazy Iterators

The for-of loop is perfectly designed to work with iterators—including infinite ones. It calls the iterator's next() method on each iteration, pulling values one at a time. This plays beautifully with lazy evaluation: nothing computes until for-of actually requests it.

But here's the catch: for-of doesn't know when to stop unless the iterator signals it's done (by returning { done: true }). With an infinite iterator, that never happens—so you must break the loop manually.


Safe Consumption of Infinite Iterators

function* infiniteCounter() {
  let n = 0;
  while (true) yield n++;
}

// Without break, this runs forever:
// for (const num of infiniteCounter()) { console.log(num); }

// Safe approach: break based on a condition
for (const num of infiniteCounter()) {
  console.log(num);
  if (num >= 5) break; // You control the exit
}
// Logs: 0, 1, 2, 3, 4, 5

Think of for-of as a curious reader flipping through an endless book. It won't stop turning pages until you close the book yourself.


Techniques for Breaking Out

  • Explicit break: Check a condition and exit.
  • Combine with take(): If you've built a lazy take() helper, it produces a finite iterator that for-of can exhaust naturally.
// Using take from earlier lessons:
function* take(iterable, n) {
  let count = 0;
  for (const value of iterable) {
    if (count++ >= n) return;
    yield value;
  }
}

for (const num of take(infiniteCounter(), 3)) {
  console.log(num); // Logs: 0, 1, 2 — stops automatically
}

Key Takeaway: for-of eagerly consumes iterators one value at a time, but infinite iterators require you to either break manually or wrap them in a helper that limits output.