Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Lazy Sequences with Generators

This lesson is built with resources from youtube.com, itnext.io and 1 more site.

Hello! Welcome to the seventh lesson in our module on Iteration Protocols and Generator Functions.

In our last lesson, we completed our tour of the generator's three-part control API by mastering iterator.throw(). We saw how it allows for sophisticated error handling and two-way communication, enabling a calling context to signal failure or cancellation to a running generator. With next(), return(), and throw(), you now have a complete toolkit for managing these pausable functions.

Now, we'll leverage this pausable nature to explore one of the most powerful and unique applications of generators.

Our learning outcome for this lesson is to: Build infinite sequences with lazy evaluation using generator functions.

An infinite sequence—like all natural numbers, or the endless stream of prime numbers—is a concept that traditional functions and data structures like arrays struggle with. You can't store an infinite list in memory. Today, you'll see how generators elegantly solve this problem through a concept called lazy evaluation.

1. The Core Concept: Eager vs. Lazy Evaluation

Before we write any code, it's crucial to understand the difference between eager and lazy evaluation. Your experience with different programming paradigms might have already exposed you to this, but let's formalize it in the context of JavaScript.

  • Eager Evaluation: This is the default in JavaScript. Expressions are evaluated and data is computed immediately. When you call .map() on an array, a new array with all the transformed elements is created right away, whether you use them all or not.
  • Lazy Evaluation: Data is only computed when it is explicitly requested. The computation is deferred until the last possible moment.

This distinction is precisely why generators are the perfect tool for handling potentially infinite data. To see this contrast in action, watch the following segment.

JavaScript Generators Explained, But On A Senior-Level

This video from the Jan Hesters channel provides an excellent, senior-level explanation of eager vs. lazy evaluation. It contrasts eager structures like arrays and promises with lazy operators.

Watch from 01:36 to 04:24. Focus on the core distinction: 'eager' means data is evaluated immediately, while 'lazy' means data is only evaluated when needed. Note the examples used for both (arrays for eager, logical operators for lazy).

As the video highlighted, an eager approach to an infinite sequence would cause a program to hang indefinitely, trying to compute and store an endless series of values. A lazy approach, however, only calculates the next value when we ask for it, making the infinite manageable.


2. Implementing an Infinite Sequence with a Generator

So, how do we build an infinite sequence? With a regular function, a while (true) loop is a recipe for a crash. With a generator, it's the standard pattern for an infinite sequence. The yield keyword is the magic ingredient that makes this safe. When the generator yields a value, its execution—including the while loop—is paused until .next() is called again.

Let's see how to implement the classic infinite Fibonacci sequence.

What are JavaScript Generators and Iterators?

Andrew Burgess's video demonstrates this concept perfectly. He'll build an infinite Fibonacci sequence generator, showing how while(true) and yield work together.

Watch the section from 07:36 to 08:27. Pay close attention to how the while(true) loop is structured and where the yield statement is placed. This is the fundamental pattern for creating any infinite generator.

Here is the code from the video, a canonical example of an infinite generator:

function* fibonacci() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    const nextA = b;
    const nextB = a + b;
    a = nextA;
    b = nextB;
  }
}

Let's trace the execution:

  1. const fib = fibonacci(); is called. The generator is created but no code inside it runs yet.
  2. fib.next(); is called. The while loop starts. yield a (0) is encountered. The generator pauses and returns { value: 0, done: false }.
  3. fib.next(); is called again. Execution resumes after the yield. The values of a and b are updated. The loop continues to the next iteration. yield a (1) is encountered. The generator pauses and returns { value: 1, done: false }.
  4. This process can continue indefinitely, with each call to next() producing the next number in the sequence. The while(true) loop never runs away because yield acts as a gate.

3. Consuming Infinite Sequences

An infinite sequence is only useful if you can consume it in a finite, controlled way. Simply using a for...of loop will lock up your program, as it will never find a { done: true } result.

const fib = fibonacci();

// DANGER: This will run forever!
// for (const num of fib) {
//   console.log(num);
// }

So, how do we safely interact with these sequences?

Method 1: Manual Iteration

The most direct method is to call .next() a specific number of times. This is great for demonstration but cumbersome for practical use.

node.js - Understanding the Need for Generator Functions ...

This Stack Overflow answer clearly demonstrates the problem with a while(true) loop in a regular function versus a generator. It then shows how to consume the generator version by manually calling next().

Read the section titled 'Easily handle extremely large or infinite streams of data'. Compare the non-working eager fibonacci function with the working lazy generator version. Note how the example consumes the first few values by repeatedly calling .next().value.

Method 2: Adding a Limit to the Generator

A simple pattern is to modify the generator to accept a limit, making it conditionally finite.

What are JavaScript Generators and Iterators?

The same video from Andrew Burgess shows how to easily adapt our infinite generator to accept a maximum value.

Watch from 08:38 to 09:27. See how a max parameter and an if check with break are added to terminate the loop, making the generator safe to use with for...of loops.

This is a good solution, but it requires modifying the original generator. What if we want to work with any iterable—finite or infinite—using a more generic approach?

Method 3: Composable Helper Functions

This is the most powerful and flexible approach, and it aligns beautifully with functional programming principles. We can create other generators that act as "iterable operators," consuming one iterable and producing a new one.

A canonical example is a take(n) function. It takes the first n items from any iterable and then stops.

node.js - Understanding the Need for Generator Functions ...

The same Stack Overflow answer introduces this advanced concept of composable helper functions. It provides implementations for skip and take, which are themselves generators.

Read the next section of the answer, starting from the text 'A generator-implemented fibonacci does not need to be altered...'. Study the implementation of the take(n, iterator) and skip(n, iterator) helper functions. Notice how they use yield and yield* to control the flow. Most importantly, see how they can be composed to perform complex, lazy queries on an infinite sequence like fibonacci() or idGenerator().

Let's create our own take function and use it with our fibonacci generator.

// A helper generator that takes the first 'n' items from any iterator.
function* take(n, iterator) {
  for (let i = 0; i < n; i++) {
    const next = iterator.next();
    if (next.done) {
      // The source iterator finished before we took 'n' items.
      return; 
    }
    yield next.value;
  }
}

// Our infinite Fibonacci generator
function* fibonacci() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b]; // More concise way to swap
  }
}

// Now we can safely use a for...of loop!
const first10Fib = take(10, fibonacci());

for (const num of first10Fib) {
  console.log(num);
}
// Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

// We can also spread it into an array because `take` makes it finite.
const fibArray = [...take(5, fibonacci())];
console.log(fibArray); // [0, 1, 1, 2, 3]

This is incredibly powerful. The fibonacci generator remains pure and infinite. The take generator is a reusable utility that can enforce a limit on any iterable. We could chain them, for example, to get the 11th through 15th Fibonacci numbers without ever calculating the entire sequence: take(5, skip(10, fibonacci())).

Test your understanding!
  1. Create an infinite generator function called idGenerator that yields unique string IDs in the format "id-1", "id-2", "id-3", and so on.
  2. Using the take helper function we just discussed, create a new iterable that represents the first 5 IDs.
  3. Use the spread syntax (...) to convert this finite iterable into an array and log it to the console.
Show answer
// 1. Create the infinite generator
function* idGenerator() {
  let i = 1;
  while (true) {
    yield `id-${i}`;
    i++;
  }
}

// Helper function from the lesson
function* take(n, iterator) {
  for (let i = 0; i < n; i++) {
    const next = iterator.next();
    if (next.done) return;
    yield next.value;
  }
}

// 2. Create the finite iterable
const first5IDs = take(5, idGenerator());

// 3. Spread it into an array and log
const idArray = [...first5IDs];
console.log(idArray);
// Expected output: ["id-1", "id-2", "id-3", "id-4", "id-5"]

This demonstrates how an infinite, lazy data source (idGenerator) can be safely and efficiently consumed by composing it with a terminating operator (take).


Conclusion

Today you've unlocked one of the most elegant features of JavaScript generators. By embracing lazy evaluation, you can represent and operate on data structures that are conceptually infinite, a task that is impossible with traditional, eager data structures like arrays.

Key Takeaways:

  • Lazy vs. Eager: Generators enable lazy evaluation, where values are computed on-demand, as opposed to eager evaluation (like array methods), where all values are computed upfront.
  • Infinite Loops Safely: A while(true) loop inside a generator is a standard pattern for creating an infinite sequence. The yield statement pauses execution, preventing the program from crashing.
  • Controlled Consumption: An infinite sequence must be consumed in a controlled manner, for example, by manually calling .next(), using a for...of loop with a break condition, or by composing it with helper generators.
  • Composable Helpers: Creating small, reusable generator functions like take(n), skip(n), or map(fn) is a powerful, declarative pattern for building complex data processing pipelines that work efficiently with both finite and infinite sources.

Next Up

This lesson concludes our deep dive into the core mechanics and primary synchronous use cases of generators. We've seen how they provide a more powerful iteration primitive than the manual iterator protocol. In our next and final lesson of this module, we will solidify this understanding by refactoring a complex manual iterator into a much cleaner and more maintainable generator function, cementing the practical benefits of everything you've learned.