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

Fibonacci as an Infinite Iterator

Implementing the Fibonacci sequence as a lazy iterator that computes terms only when requested.

Fibonacci as an Infinite Iterator

You'll learn how to generate Fibonacci numbers on-demand using lazy iteration, never computing more than needed.


The Fibonacci sequence (0, 1, 1, 2, 3, 5, 8...) is perfect for lazy iteration because you don't always need the millionth term—you might only want the first 10. By implementing Fibonacci as an infinite iterator, you calculate each number only when requested, keeping memory usage minimal and computation efficient.

Building the Fibonacci Iterator

You create an object with a next() method that tracks the previous two Fibonacci numbers internally. Each call to next() computes the next term by adding those two values, then shifts them forward:

function fibonacciIterator() {
  let prev = 0;
  let curr = 1;
  
  return {
    next() {
      const value = prev;
      [prev, curr] = [curr, prev + curr]; // Shift forward
      return { value, done: false }; // Never done!
    }
  };
}

const fib = fibonacciIterator();
console.log(fib.next().value); // 0
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2
console.log(fib.next().value); // 3

Notice done is always false—this iterator could theoretically run forever. You control how many terms you need by stopping iteration yourself.

Making It Iterable

To use it with loops, make it iterable by adding Symbol.iterator:

function fibonacci() {
  return {
    [Symbol.iterator]: fibonacciIterator
  };
}

// Take only the first 8 terms
let count = 0;
for (const num of fibonacci()) {
  if (count++ >= 8) break;
  console.log(num); // 0, 1, 1, 2, 3, 5, 8, 13
}

Key Takeaway: Fibonacci as an infinite iterator computes terms lazily—you generate numbers on-the-fly without precomputing or storing the entire sequence, combining efficiency with the elegance of iteration protocols.