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

Pitfalls of Infinite Iterators

Common mistakes: accidentally consuming infinite sequences and losing track of termination.

Pitfalls of Infinite Iterators

You'll learn: The common mistakes that can freeze your program when working with infinite iterators and how to avoid them.

Infinite iterators are powerful, but they're also dangerous. Unlike finite arrays that eventually run out of elements, infinite iterators never stop. This means certain operations that work perfectly on regular arrays will hang your program indefinitely.

The Core Problem: Accidental Consumption

The biggest pitfall is accidentally consuming an infinite sequence. Many array methods and operations expect to reach an end—spreading with [...], calling Array.from(), or using eager methods like .reduce() or .forEach() on infinite iterators will run forever.

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

// 🚫 DANGER: These will freeze your program
// const arr = [...infinite()];        // Never completes
// Array.from(infinite());             // Never completes
// for (const x of infinite()) { }     // Runs forever

Losing Track of Termination

Another pitfall is forgetting to include a termination condition. Even when you intend to use lazy operations, you must eventually limit the sequence with techniques like taking only N elements or breaking when a condition is met.

// ✅ SAFE: Always limit infinite iterators
function* infinite() {
  let n = 0;
  while (true) yield n++;
}

// Take only what you need
const first10 = [];
const iter = infinite();
for (let i = 0; i < 10; i++) {
  first10.push(iter.next().value);
}

Think of infinite iterators like a faucet that never turns off—you must remember to close it, or your sink overflows.

Key Takeaway: Never consume infinite iterators with eager operations like spreading or Array.from(). Always explicitly limit them with counters, breaks, or bounded iteration before materializing values.