Skip to main content

Welcome to a Grasp lesson

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

Lesson 13

Delegating Iteration with `yield*`

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! Welcome to the fifth lesson in our module on generator functions.

In our last lesson, we explored the powerful two-way communication capabilities of generators, using next(value) to pass information into a running generator. This revealed that generators are not just simple data producers but are in fact interactive coroutines.

Today, we'll address a new question: how do we compose generators? If you have one generator that needs to yield all the values from another, how do you do it efficiently? This lesson focuses on the elegant solution to that problem.

Our learning outcome is to: Delegate iteration to another iterable or generator using yield*.

By the end of this lesson, you will be able to:

  • Understand why simply calling one generator from another doesn't work as expected.
  • Use the yield* operator to seamlessly delegate iteration to other generators or any iterable object (like arrays and strings).
  • Appreciate the power of yield* in simplifying code, especially for recursive data structures.

1. The Challenge: Composing Generators

Let's say you have a generator function and, inside it, you want to yield all the values from a second generator. Given your CS background, your first instinct might be to just call the second function. Let's see what happens.

function* numberGenerator() {
  yield 2;
  yield 3;
}

function* mainGenerator() {
  yield 1;
  numberGenerator(); // Will this work?
  yield 4;
}

const iterator = mainGenerator();

console.log([...iterator]); // What do you expect the output to be?
// Output: [ 1, 4 ]

The values 2 and 3 are missing. Why? Because calling numberGenerator() simply creates a new, unused iterator object that is immediately discarded. The mainGenerator never actually consumes it.

You could manually iterate over the inner generator with a for...of loop, but this adds boilerplate:

function* mainGeneratorWithLoop() {
  yield 1;
  for (const value of numberGenerator()) {
    yield value;
  }
  yield 4;
}

console.log([...mainGeneratorWithLoop()]); // [ 1, 2, 3, 4 ]

This works, but JavaScript provides a much cleaner and more powerful syntax for this exact purpose: yield*.


2. The Solution: yield* Delegation

The yield* operator is designed to delegate iteration. It effectively "unpacks" an iterable, yielding each of its items individually until it's exhausted.

Let's watch a quick and direct explanation of this operator.

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

This short segment from the 'Professional Modern JavaScript' series by basarat clearly introduces the yield* syntax and its basic usage.

Watch the clip from 08:00 to 08:57. Pay attention to how yield* is used with both another generator and a standard array.

As you saw, yield* works on any iterable object. This includes:

  • Other generators
  • Arrays
  • Strings
  • Maps and Sets
  • The arguments object

Here’s our previous example, rewritten using yield*:

function* numberGenerator() {
  yield 2;
  yield 3;
}

function* mainGenerator() {
  yield 1;
  yield* numberGenerator(); // Delegate to numberGenerator
  yield 4;
  yield* [5, 6];          // Delegate to an array
  yield* "Go!";           // Delegate to a string
}

console.log([...mainGenerator()]);
// Output: [ 1, 2, 3, 4, 5, 6, 'G', 'o', '!' ]

This is far more concise and expressive.


3. Under the Hood: True Delegation

While yield* anotherIterable looks like syntactic sugar for a for...of loop, it's more powerful. It establishes a transparent pipeline between the outer generator's caller and the inner (delegated) iterator.

To understand this mechanism, let's turn to the definitive source.

yield* - JavaScript - MDN Web Docs

The MDN Web Docs for yield* provides a precise technical description of its behavior, including how it forwards method calls.

First, read the 'Description' section to understand the core mechanism. Then, read the section on 'Method forwarding'. Focus on the idea that calls to .next(), .throw(), and .return() on the main generator are passed through to the delegated iterator.

The key takeaway is that yield* doesn't just pull values out; it forwards calls.

  • When you call mainIterator.next(value), yield* forwards that call to delegatedIterator.next(value).
  • The result object { value, done } from the delegated iterator is passed directly back to the original caller.
  • This also applies to throw() and return(), which is crucial for error handling and cleanup, a topic we'll cover in the next lesson.

This transparent forwarding makes yield* a true delegation mechanism, not just a simple loop.


4. A Powerful Application: Recursive Traversal

The ability to delegate makes yield* exceptionally well-suited for iterating over recursive data structures. With your CS background, you'll recognize the elegance of this approach for tree traversal.

The following resource shows how to implement an iterator for a binary tree using yield*.

Synchronous generators ES6 (advanced)

The book 'Exploring JS' by Dr. Axel Rauschmayer contains a perfect example of using yield* for iterating over a binary tree. This demonstrates a practical and powerful use case.

Read the subsection titled 'Example: Iterating over a tree'. Observe how the recursive call yield* this.left simplifies the pre-order traversal logic immensely.

Let's analyze that code:

class BinaryTree {
  constructor(value, left = null, right = null) {
    this.value = value;
    this.left = left;
    this.right = right;
  }

  // Implement the iterable protocol with a generator
  * [Symbol.iterator]() {
    // 1. Yield the current node's value
    yield this.value;
    
    // 2. If a left child exists, delegate iteration to it
    if (this.left) {
      yield* this.left;
    }
    
    // 3. If a right child exists, delegate iteration to it
    if (this.right) {
      yield* this.right;
    }
  }
}

const tree = new BinaryTree('a',
  new BinaryTree('b', new BinaryTree('c'), new BinaryTree('d')),
  new BinaryTree('e')
);

// Because the tree is iterable, we can use for...of
for (const value of tree) {
  console.log(value); // a, b, c, d, e
}

Without yield*, implementing this iterator would require managing an explicit stack to keep track of the nodes to visit. With yield*, the generator machinery and the call stack handle that complexity for us, resulting in clean, readable, and declarative code.

Test your understanding!

A classic use case for this pattern is flattening a nested array. Create a generator function flatten(arr) that takes an array with nested arrays and yields all the numbers in a single, flat sequence.

For example:

const nestedArray = [1, [2, 3], [4, [5]]];
const flattener = flatten(nestedArray);
console.log([...flattener]); // Should output: [1, 2, 3, 4, 5]

Hint: If an element is an array, delegate to a recursive call. If it's not, yield it directly.

Show answer
function* flatten(arr) {
  for (const item of arr) {
    if (Array.isArray(item)) {
      // If the item is an array, delegate the flattening process to it
      yield* flatten(item);
    } else {
      // Otherwise, it's a value we can yield directly
      yield item;
    }
  }
}

// Let's test it:
const nestedArray = [1, [2, 3], [4, [5]]];
const flattener = flatten(nestedArray);

console.log([...flattener]); // [ 1, 2, 3, 4, 5 ]

Conclusion

You've now learned how to compose iterators and generators using yield*, a powerful tool for creating modular and clean iteration logic.

Key Takeaways:

  • yield* delegates iteration from a generator to another iterable object.
  • It provides a concise way to "chain" or compose generators, superior to manual iteration with a for...of loop.
  • It's particularly effective for implementing iterators for recursive data structures like trees or nested lists.
  • yield* performs true delegation by forwarding calls to .next(), .throw(), and .return(), creating a transparent channel to the underlying iterator.

Next Up

The concept of yield* forwarding method calls is a crucial one. What happens if an error occurs in a delegated generator? How does the main generator find out? In our next lesson, we will dive into error handling by exploring the generator.throw() method and see how it interacts with the yield* delegation model.