Skip to main content

Welcome to a Grasp lesson

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

Lesson 11

Mastering Generator Functions: `function*` and `yield`

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

Hello! Let's dive into the third lesson of our module on iteration.

In our last session, you mastered the art of manually implementing the iterator protocol. You built a custom Matrix class that could be used in a for...of loop by meticulously managing the iteration state (x and y coordinates) within a next() method. While powerful, you probably noticed it required a fair bit of boilerplate code to track state and structure the { value, done } return objects.

Today, we'll learn about a much more elegant solution to this problem. The learning outcome for this lesson is to: Create generator functions using function* syntax and the yield keyword.

Generators are a special kind of function that can pause their execution and resume it later. This capability allows them to produce a sequence of values over time, effectively acting as factories for iterators, but with a vastly simplified and more readable syntax. By the end of this lesson, you will understand:

  • The core concept of a pausable function.
  • How to define a generator using function*.
  • How the yield keyword pauses execution and provides a value.
  • How generators simplify the creation of custom iterables, directly replacing the manual patterns we learned previously.

1. The Core Idea: Pausable Functions

A regular JavaScript function follows a "run-to-completion" model. Once you call it, it runs until it hits a return statement or the end of its body. You cannot pause it in the middle and resume it later.

Generators break this model. They introduce a form of cooperative multitasking into your functions, allowing you to define a block of code that can yield control back to the caller, and then be resumed exactly where it left off.

This diagram provides a great mental model for the difference.

Normal Functions vs. Generators Execution Flow
This diagram contrasts a normal function's single, continuous execution flow with a generator's ability to start, pause at a `yield` statement, and then resume on a subsequent call.

From your computer science background, you can think of a generator as a language-level implementation of a coroutine or a state machine. The JavaScript engine automatically saves the function's state (including local variables and the exact point of execution) each time it pauses.


2. Generator Syntax: function* and yield

To create a generator, you use a special syntax: function* (the asterisk can also be placed after the function keyword, as in function *myGenerator(), but function* is more common). Inside a generator, you use the yield keyword instead of return to produce a value in the sequence.

Let's begin with a foundational reading that covers this syntax.

Generators

The article 'Generators' on javascript.info provides an excellent, clear introduction to the fundamental syntax and behavior. We'll start here.

Please read the first section, titled 'Generator functions'. Focus on the function* syntax, how yield works, and the structure of the object returned by next() ({value, done}).

As the article explained, two crucial things happen:

  1. Calling a generator function does not execute its code. Instead, it returns a generator object. This object is an iterator.
  2. You use the next() method on this generator object to start (or resume) execution. The code runs until it hits the next yield statement.

3. Visualizing the Execution Flow

This pause-and-resume behavior is the most important concept to grasp. Watching it happen step-by-step is more effective than just reading about it. The following video uses console.log statements to clearly show when different parts of the generator function are executed.

generators, function*, yield, yield* // Professional Modern JavaScript

This video from the 'Professional Modern JavaScript' series provides a dynamic walkthrough of the generator execution lifecycle.

Watch the first three minutes and twenty-six seconds (from 00:00 to 03:26). Pay close attention to: The fact that the initial function call only creates the generator object. How each call to .next() resumes execution until the next yield is encountered. The value and done properties of the object returned by .next().

To summarize the lifecycle you just saw:

  • const gen = myGenerator(); — The generator function's code is paused at the very top. A generator object gen is created.
  • gen.next(); — Execution starts. It runs until it hits the first yield, then pauses. The value from the yield is returned in { value: ..., done: false }.
  • gen.next(); — Execution resumes right after the previous yield. It runs until it hits the second yield, then pauses again.
  • This continues until the function finishes. The final gen.next() call after all yields are processed returns { value: undefined, done: true }.

4. The Real Power: Generators as Iterables

Manually calling next() is great for control and for understanding the mechanics. However, the true convenience of generators is that they automatically conform to the iterable protocol. Because the generator object has a next() method, it's an iterator. And because it also has a [Symbol.iterator]() method that returns itself, it's also an iterable.

This means you can use generators directly in any context that expects an iterable, like a for...of loop or the spread operator (...).

Generators

Let's revisit the javascript.info article to see how seamlessly generators integrate with JavaScript's iteration constructs.

Now, read the section 'Generators are iterable'. This will connect the dots and show you why generators are the preferred way to create iterables.

This is the payoff: all the manual work of creating an iterator object, managing state, and returning { value, done } is handled for you by the generator's syntax.


5. Practical Application: A Clean Refactor

Let's make this concrete by refactoring the kind of manual iterator we built in the previous lesson. Remember the MyRange class? We can now dramatically simplify its [Symbol.iterator] method.

First, let's watch a quick video that does exactly this for a range function.

generators, function*, yield, yield* // Professional Modern JavaScript

This segment from the 'Professional Modern JavaScript' video demonstrates how to create a simple range generator, which is a perfect stand-in for our MyRange class.

Watch the segment from 03:46 to 05:13. Notice how a simple for loop combined with yield replaces all the manual state management.

Now, let's apply that principle to our class-based iterator from the last lesson.

Before: Manual Iterator (from Lesson 2.2)

class MyRange {
  constructor(start, end) {
    this.start = start;
    this.end = end;
  }

  [Symbol.iterator]() {
    let current = this.start;
    const end = this.end;

    return { // Return a separate iterator object
      next() {
        if (current <= end) {
          return { value: current++, done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
}

After: Using a Generator

class MyRange {
  constructor(start, end) {
    this.start = start;
    this.end = end;
  }

  // Use a generator for the iterator!
  *[Symbol.iterator]() {
    for (let current = this.start; current <= this.end; current++) {
      yield current;
    }
  }
}

const range = new MyRange(1, 3);
console.log([...range]); // [1, 2, 3] -> It just works!

The generator version is not only shorter but also much easier to read and reason about. The logic is a straightforward for loop, and the yield keyword takes care of all the pausing, state-saving, and object-wrapping mechanics for us.

Test your understanding!

In the previous lesson, you created an iterable Matrix class that iterated over its elements in row-major order. Your task is to refactor its [Symbol.iterator]() method to use a generator.

Here is the class structure to start with:

class Matrix {
  constructor(matrix) {
    this.data = matrix;
    this.height = matrix.length;
    this.width = matrix.length > 0 ? matrix[0].length : 0;
  }

  // Refactor this method to be a generator
  [Symbol.iterator]() {
    let y = 0;
    let x = 0;
    
    return {
      next: () => {
        if (y >= this.height) {
          return { done: true };
        }
        const value = this.data[y][x];
        x++;
        if (x >= this.width) {
          x = 0;
          y++;
        }
        return { value: value, done: false };
      }
    };
  }
}

const myMatrix = new Matrix([
  [1, 2],
  [3, 4],
]);

// After your refactor, this code should still work and output [1, 2, 3, 4]
console.log([...myMatrix]);

Hint: You can use nested for loops to iterate through the rows and columns.

Show answer

Here is the refactored Matrix class using a generator:

class Matrix {
  constructor(matrix) {
    this.data = matrix;
    this.height = matrix.length;
    this.width = matrix.length > 0 ? matrix[0].length : 0;
  }

  // Refactored to a generator method
  *[Symbol.iterator]() {
    for (let y = 0; y < this.height; y++) {
      for (let x = 0; x < this.width; x++) {
        yield this.data[y][x];
      }
    }
  }
}

const myMatrix = new Matrix([
  [1, 2],
  [3, 4],
]);

console.log([...myMatrix]); // Outputs: [1, 2, 3, 4]

const myOtherMatrix = new Matrix([
  ['a', 'b', 'c'],
  ['d', 'e', 'f'],
]);

for (const element of myOtherMatrix) {
    console.log(element); // Outputs: a, b, c, d, e, f
}

As you can see, the complex logic of manually incrementing x and y and checking boundary conditions inside the next method is completely replaced by a simple, intuitive nested loop structure.


Conclusion

Today you've added a major tool to your advanced JavaScript toolkit. You've seen how generator functions provide a clean, powerful, and highly readable syntax for creating iterators.

Key Takeaways:

  • Generator functions are declared with function* and use the yield keyword.
  • They are pausable: calling them returns a generator object, and next() controls execution.
  • yield pauses the function, saves its state, and produces the next value in the iteration.
  • Generators are natively iterable, working seamlessly with for...of, spread syntax, and other iteration-consuming features.
  • They are the modern, preferred way to implement custom iteration logic in JavaScript, replacing verbose manual iterator implementations.

Next Up

So far, we have only used yield to send data out of a generator. But what if we could send data back in? In our next lesson, we will explore the two-way communication capabilities of generators by passing values into a running generator using the next(value) method. This unlocks even more advanced patterns for controlling asynchronous flows and managing complex state.