Skip to main content

Welcome to a Grasp lesson

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

Lesson 16

From Manual Iterators to Generator Functions

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

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

Over the past few lessons, we've explored every facet of generator functions: the function* and yield syntax, their pausable nature, the three-part control API (next, return, throw), and their power in creating infinite sequences through lazy evaluation.

So far, we've treated generators as a new feature to learn in isolation. Today, we connect all the dots and answer the fundamental question: why were generators added to JavaScript? You'll see that they are not just an interesting curiosity but a powerful tool designed to solve a very specific and common problem.

Our learning outcome for this lesson is to: Refactor a complex iteration from a manual iterator implementation to a more concise generator function.

We will take a custom, non-iterable data structure, first make it iterable the "hard way" by manually implementing the iterator protocol, and then refactor that implementation into a much cleaner and more intuitive generator. This process will cement the practical value of everything you've learned in this module.

1. The Challenge: Iterating a Custom Data Structure

Native JavaScript data structures like Arrays, Maps, and Sets are iterable out of the box. But what happens when you create your own, like a tree or a linked list? You can't use a for...of loop on them directly.

Let's use a Linked List as our case study. Given your CS background, you'll be familiar with this data structure. It's a classic example of something that requires a custom traversal algorithm.

The JavaScript Iteration Protocols and How They Fit In

The article 'The JavaScript Iteration Protocols and How They Fit In' by Ken Bellows provides the perfect foundation for our lesson. We will follow its excellent case study on a Linked List.

First, read the introductory sections 'Case Study: Linked Lists' and 'Linked Lists the Old-School Way'. This will introduce the LinkedList class we'll be working with. Pay attention to the forEach method, which represents a traditional, non-iterable way of traversing the list.

The forEach method shown in the article works, but it's a custom solution. It doesn't compose with the rest of the JavaScript ecosystem. You can't use the spread syntax (...), for...of, Array.from(), or other language features that expect an iterable.


2. The "Hard Way": Manual Iterator Implementation

To make our LinkedList class a true, first-class citizen in JavaScript, we need to make it iterable. As we briefly covered in an earlier lesson, this means implementing the [Symbol.iterator] method. This method must return an iterator—an object with a next() method that returns objects of the shape { value: ..., done: ... }.

This is the "manual" way. It involves explicitly managing the state of the iteration (what is the current node?) and manually constructing the result object for every step.

The JavaScript Iteration Protocols and How They Fit In

Now, let's see how the article makes the LinkedList iterable by manually implementing the protocol. This is the 'before' state of our refactor.

Read the sections 'The Iteration Protocols' for a quick refresher, and then 'Iterable Linked Lists'. Focus on the implementation of the [Symbol.iterator] method. Note the boilerplate: a curr variable to hold state, and a returned object with a next method that has to check curr and return { value, done } objects explicitly.

The manual implementation looks like this:

class LinkedList {
    // ... constructor and push methods ...

    [Symbol.iterator]() {
        let curr = this.head; // State is managed here
        return {
            next() { // The iterator object with its next() method
                if (curr === null) {
                    return { done: true }; // Manual return object
                }
                else {
                    const result = { value: curr.val, done: false }; // Manual return object
                    curr = curr.next; // Manually advance state
                    return result;
                }
            }
        };
    }
}

This code works, and our LinkedList is now compatible with for...of. However, it's verbose and clunky. The logic of the iteration is wrapped in a significant amount of boilerplate code. The state (curr) lives inside a closure, and we're manually crafting those { value, done } objects. This is precisely the "complex iteration" our learning outcome describes.


3. The "Easy Way": Refactoring to a Generator

Now, let's refactor this code using a generator. Remember that a generator function, when called, automatically returns an object that fulfills both the iterable and iterator protocols. The yield keyword handles the pausing and the creation of the { value: ..., done: false } objects for us.

This visual provides a quick recap of how a generator's execution flow differs from a normal function, enabling this "pausing" behavior.

Normal Functions vs. Generators Execution Flow
This diagram contrasts a normal function's single execution path with a generator's ability to pause at `yield` points and resume later, which is the mechanism that simplifies iterator creation.

Now, let's apply this to our LinkedList.

The JavaScript Iteration Protocols and How They Fit In

The same article shows the beautiful simplicity of refactoring our manual iterator into a generator. This is the 'after' state.

Read the sections 'Generators' and 'Linked Lists with Generators!'. This is the core of our lesson. Compare the new *[Symbol.iterator]() generator method with the manual one from the previous step. The transformation should be striking.

Here is the refactored code. The change is remarkable.

class LinkedList {
    // ... constructor and push methods ...

    *[Symbol.iterator]() { // Note the *
        let curr = this.head;
        while (curr !== null) {
            yield curr.val; // Just yield the value!
            curr = curr.next;
        }
    }
}

Let's analyze the improvement:

  1. No More Boilerplate: We no longer need to return an object with a next() method. The function* syntax takes care of that.
  2. No Manual Result Objects: We don't write return { value: ..., done: ... }. The yield keyword produces the { value: curr.val, done: false } object, and the function's completion implicitly produces the final { value: undefined, done: true } object.
  3. Improved Readability: The logic inside the generator is now almost identical to the simple while loop we might have written in the old forEach method. It clearly and linearly describes the process of walking the list. All the complex state-machine mechanics of the iterator protocol are handled by the JavaScript engine.

This is the primary reason generators were introduced: to provide clean, high-level syntax for the common task of creating iterators.


4. Practice: Refactoring another Iterator

To solidify your understanding, let's look at one more direct comparison. The following resource shows the same refactoring pattern applied to a simple range object.

Generators

The article 'Generators' on javascript.info provides another excellent, compact example of this refactoring process. It shows a custom 'range' object first built with a manual iterator, then refactored into a much cleaner generator.

Read the section titled 'Using generators for iterables'. Compare the two code blocks for the range object: the first with the manual [Symbol.iterator] implementation, and the second, more compact version that uses a generator function.

Now, it's your turn to perform a refactor.

Test your understanding!

Here is a function that returns an iterator for a pseudo-random number sequence. It uses a closure to maintain the value state between calls to next(). Your task is to refactor this into a generator function named pseudoRandomGenerator that produces the same infinite sequence of numbers.

// Manual iterator implementation using a closure
function pseudoRandomManual(seed) {
  let value = seed;
  
  return {
    next: function() {
      value = value * 16807 % 2147483647;
      return { done: false, value: value };
    }
  };
}

// --- Your refactored generator function here ---
// function* pseudoRandomGenerator(seed) { ... }


// --- Testing your code ---
const manualIterator = pseudoRandomManual(1);
console.log(manualIterator.next().value); // Expected: 16807
console.log(manualIterator.next().value); // Expected: 282475249

// const generator = pseudoRandomGenerator(1);
// console.log(generator.next().value); // Should be 16807
// console.log(generator.next().value); // Should be 282475249
Show answer
function* pseudoRandomGenerator(seed) {
  let value = seed;
  
  while (true) {
    value = value * 16807 % 2147483647;
    yield value;
  }
}

// --- Testing the refactored code ---
const generator = pseudoRandomGenerator(1);
console.log(generator.next().value); // 16807
console.log(generator.next().value); // 282475249
console.log(generator.next().value); // 1622650073

Notice how the logic is simplified. The state (value) is a simple local variable, and the while(true) loop (which you learned about in the previous lesson) elegantly defines the infinite sequence without the boilerplate of the manual next() function.


5. A Broader Perspective: Iterating Over Events

So far, we've refactored the iteration of data structures. But the pattern is even more powerful. Generators can be used to manage any complex, stateful sequence of events, transforming what would otherwise be a tangled mess of callbacks into a clean, linear script.

A fantastic real-world example is in animation libraries.

I actually use JavaScript generator functions

To see how far this concept can go, let's look at a real-world use case. Joshua Morony explains how the 'Motion Canvas' animation library uses generators to orchestrate complex animation sequences.

Watch from 02:38 to 04:30. The key idea is that a runScene function 'iterates' over a generator. Each yield pauses the animation, perhaps to wait for a duration or delegate to another animation sequence via yield*. This turns complex, time-based logic into a simple, readable script.

This example shows that "iteration" doesn't just mean looping over data. It can mean stepping through any process that has distinct, pausable stages. This is a profound shift in thinking and a key reason why generators are a cornerstone of advanced JavaScript, especially as a precursor to async/await.


Conclusion

This lesson brought together everything we've learned about generators, demonstrating their primary purpose: to provide an elegant and concise syntax for implementing the iteration protocol.

Key Takeaways:

  • The Problem: Manually implementing the iterator protocol on custom objects is verbose, state-management is complex, and the code is hard to read.
  • The Solution: Generators are syntactic sugar for creating iterators. They handle the boilerplate of creating the iterator object and the { value, done } results.
  • The Refactor: Iteration logic inside a generator often looks like a simple, synchronous loop (for, while), making it vastly more readable and maintainable than a manual implementation.
  • The Benefit: By using generators to make your custom objects iterable, you integrate them seamlessly with the rest of the JavaScript language (for...of, spread syntax, etc.).

You have now completed the module on Iteration Protocols and Generator Functions. You have a deep understanding of how to create, control, and consume custom iteration in synchronous JavaScript.


Next Up

Our journey into advanced JavaScript continues. Having mastered synchronous iteration, we will now venture into the asynchronous world. In the first lesson of our next module, Advanced Asynchronous Patterns, we will explore the async iterator protocol and how it allows us to iterate over data that arrives over time, like chunks of a file from a network stream. You will see that the concepts you learned here have a direct and powerful parallel in async programming.