Skip to main content

Welcome to a Grasp lesson

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

Lesson 12

Sending Data to Generators with `next(value)`

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

Hello! Welcome to the fourth lesson in our module on iteration protocols and generators.

In our previous lesson, you saw how generator functions (function*) and the yield keyword provide a clean and concise way to create custom iterators. We focused on how yield sends a stream of values out from the generator. This simplified the process of making classes like Matrix iterable.

Today, we're going to unlock a more powerful capability of generators. The yield keyword isn't just a one-way street for sending data out; it's a two-way communication channel. Our learning outcome is to: Pass values into a running generator using the next(value) method for two-way communication.

By the end of this lesson, you will understand how to:

  • Use yield as an expression that receives a value.
  • Control a generator's internal state and behavior from the outside by passing arguments to next().
  • Appreciate the foundational role this mechanism played in the development of modern asynchronous JavaScript (async/await).

1. "yield" is a Two-Way Street

The key conceptual shift in this lesson is to stop thinking of yield as just a statement (like return) and start seeing it as an expression that evaluates to a value.

So, where does this value come from? It comes from the argument passed to the generator.next() method when the generator is resumed.

This concept is explained exceptionally well in the following article. It uses a "ping-pong" or question-and-answer analogy that makes the flow of data easy to follow.

Generators

The article 'Generators' on javascript.info has a dedicated section that perfectly illustrates this two-way communication. It will form the foundation for our understanding.

Please read the section titled '“yield” is a two-way street' and the more elaborate example that follows it. Focus on how the value passed into generator.next(arg) becomes the result assigned to the variable on the left of the yield expression.

To solidify this idea, let's look at a visual representation of this data flow.

Generators as Two-Way Communicators
This diagram shows the execution flow. When `next()` is called, the generator runs until it hits `yield`. The value on the right of `yield` (e.g., `1`) is sent out. The generator then pauses. When `next(9)` is called again, the value `9` is sent back into the generator, becoming the resolved value of the `yield` expression itself.

2. The Execution Flow in Detail

Let's break down the sequence from the article.

function* gen() {
  // `yield` sends a question out and then pauses, waiting for an answer.
  let result = yield "2 + 2 = ?"; // Pauses here

  // When resumed, `result` will be the value passed to next().
  console.log("The answer is: " + result); 
}

let generator = gen();

// 1. Start the generator
let question = generator.next().value; // The argument to this first next() is ignored.
console.log(question); // Outputs: "2 + 2 = ?"

// The generator is now paused at the `yield` expression.
// We can do other things here...

// 2. Resume the generator, passing the "answer" back in.
generator.next(4); // Outputs: "The answer is: 4"

There is a crucial, asymmetric detail here:

The argument passed to the first next() call is always ignored. This is because when you first start the generator, there is no yield expression waiting to receive a value. The first next() call's only job is to run the code until the first yield. Subsequent next(value) calls then send a value to that now-suspended yield expression.


3. Practical Example: A Controllable Generator

This two-way communication allows the calling code to influence the generator's internal state while it's running.

Let's watch a short, senior-level explanation that demonstrates passing numbers into a generator to affect its calculations.

JavaScript Generators Explained, But On A Senior-Level

The video 'JavaScript Generators Explained, But On A Senior-Level' by Jan Hesters has a concise segment that directly demonstrates passing values in.

Watch the segment from 07:00 to 07:55. Observe how the value passed into the second and third next() calls becomes the result of the yield expressions inside the generator.

Building on that idea, the MDN documentation for yield provides another excellent example of a controllable counter. Let's analyze it.

function* counter(value) {
  while (true) {
    // 1. `yield` sends the current `value` out.
    // 2. It then pauses, waiting for an input.
    // 3. When resumed, `step` gets the value from `next(step)`.
    const step = yield value++;

    // If a `step` value was provided, adjust the internal `value`.
    if (step) {
      value += step;
    }
  }
}

const generatorFunc = counter(0);

console.log(generatorFunc.next().value);    // 0
console.log(generatorFunc.next().value);    // 1 (value++ from previous yield)
console.log(generatorFunc.next().value);    // 2 (value++ from previous yield)

// Now, let's take control!
// We pass 10 in. `step` becomes 10. `value` becomes 2 + 10 = 12.
// The `yield` then sends out the new `value` (12) and increments it to 13 for the next run.
console.log(generatorFunc.next(10).value);  // 13 (yields 12, then value becomes 13 from value++) -> Let's correct this.

// Let's trace that last call carefully:
// - `next(10)` is called. The generator resumes.
// - `const step = yield value++` completes. `step` is now `10`. Before the `yield`, `value` was 3. `value++` yields 3, then increments `value` to 4.
// - `if (step)` is true. `value` (which is 4) becomes `4 + 10 = 14`.
// - The `while` loop repeats.
// - The next `yield value++` is executed. It yields the current `value` (14) and then increments it to 15.
// So, the result is 14.

// Corrected trace:
const gen = counter(0);
console.log(gen.next().value);    // 0 (value is now 1)
console.log(gen.next().value);    // 1 (value is now 2)
console.log(gen.next().value);    // 2 (value is now 3)
console.log(gen.next(10).value);  // 14 (resumes with step=10, value becomes 3+10=13, yields 13, value becomes 14) Wait, no. Let's re-read the MDN example carefully.

/*
function* counter(value) {
  while (true) {
    const step = yield value++;
    if (step) {
      value += step;
    }
  }
}
*/
// My trace was slightly off. The `value++` happens *after* the yield resolves.
// No, the post-increment operator returns the value *before* incrementing.
// Let's trace again, very carefully.

// 1. `gen = counter(0)`: Generator created. `value` = 0.
// 2. `gen.next()`: No argument. `yield value++` is hit. It yields `0`, then `value` becomes `1`. Paused.
// 3. `gen.next()`: No argument. Resumes. `step` is `undefined`. Loop continues. `yield value++` is hit. It yields `1`, then `value` becomes `2`. Paused.
// 4. `gen.next()`: No argument. Resumes. `step` is `undefined`. Loop continues. `yield value++` is hit. It yields `2`, then `value` becomes `3`. Paused.
// 5. `gen.next(10)`: Resumes. `step` becomes `10`. `if (step)` is true. `value` (which is 3) becomes `3 + 10 = 13`. Loop continues. `yield value++` is hit. It yields `13`, then `value` becomes `14`. Paused.
// 6. `gen.next()`: No argument. Resumes. `step` is `undefined`. Loop continues. `yield value++` is hit. It yields `14`, then `value` becomes `15`. Paused.
// 7. `gen.next(10)`: Resumes. `step` is `10`. `if (step)` is true. `value` (which is 15) becomes `15 + 10 = 25`. Loop continues. `yield value++` is hit. It yields `25`, then `value` becomes `26`. Paused.

// The MDN example's output seems to have a slight discrepancy, let's use the logic derived here. The key is understanding the mechanism.
// `yield value++` is what causes the standard increment, and `value += step` is the externally controlled jump.

This pattern is powerful because it encapsulates state (value) within the generator, but provides a controlled API (next(step)) for the outside world to interact with and modify that state.

Test your understanding!

Create a generator function createAccumulator(initialValue) that works as follows:

  1. It initializes an internal accumulator to initialValue.
  2. In a loop, it yields the current value of the accumulator.
  3. The value passed into next(newValue) should be added to the accumulator.
  4. If next() is called with no arguments (or undefined), it should add 1 to the accumulator by default.

Here's how it should be used:

const accumulator = createAccumulator(10);

console.log(accumulator.next().value); // Should log: 10
console.log(accumulator.next().value); // Should log: 11 (default increment of 1)
console.log(accumulator.next(4).value);  // Should log: 15 (11 + 4)
console.log(accumulator.next().value); // Should log: 16 (default increment of 1)
console.log(accumulator.next(10).value); // Should log: 26 (16 + 10)
Show answer
function* createAccumulator(initialValue) {
  let accumulator = initialValue;

  while (true) {
    // `yield` sends the current value out and waits for an input.
    const term = yield accumulator;

    // If `term` is a number, add it. Otherwise, add the default of 1.
    if (typeof term === 'number') {
      accumulator += term;
    } else {
      accumulator += 1;
    }
  }
}

// Testing the accumulator
const accumulator = createAccumulator(10);

console.log(accumulator.next().value); // 10 (initial yield)
console.log(accumulator.next().value); // 11 (resumed with `term = undefined`, so accumulator becomes 10 + 1)
console.log(accumulator.next(4).value);  // 15 (resumed with `term = 4`, so accumulator becomes 11 + 4)
console.log(accumulator.next().value); // 16 (resumed with `term = undefined`, so accumulator becomes 15 + 1)
console.log(accumulator.next(10).value); // 26 (resumed with `term = 10`, so accumulator becomes 16 + 10)


4. The "Why": A Stepping Stone to async/await

This two-way communication isn't just a novelty; it was the mechanism that enabled a revolution in asynchronous JavaScript. Before async/await was added to the language, developers used libraries like co to write asynchronous code that looked synchronous. This was all built on generators.

The core idea was:

  1. A generator would yield a Promise.
  2. A special "runner" function would receive that Promise.
  3. The runner would wait for the Promise to resolve.
  4. Once resolved, the runner would call next() on the generator, passing the Promise's resolved value back in.

This process effectively paused the "synchronous-looking" code until the asynchronous operation was complete. async/await is, in essence, highly optimized syntactic sugar built on this exact generator-based concept.

The following video provides a brilliant deep-dive by recreating a co-like runner function from scratch. It's a bit longer, but given your background in CS and your goal to understand advanced internals, this will provide a profound "aha!" moment.

Generators in JavaScript - What, Why and How - FunFunFunction #34

The classic video 'Generators in JavaScript - What, Why and How' from Fun Fun Function demonstrates how this two-way communication is the engine behind modern async patterns.

Watch the segment from 09:53 to 17:35. In this part, the presenter builds a custom run function. Your goal is to see how he uses iterator.next(value) to push the resolved value of a promise back into the generator, allowing it to proceed to the next line.

Watching that, you can see the direct line from iterator.next(resolvedValue) to the behavior of const result = await somePromise;.


Conclusion

You've now moved beyond using generators as simple value producers to understanding them as powerful, interactive coroutines. This two-way communication is a fundamental aspect of their design.

Key Takeaways:

  • yield is an expression that can both produce a value and receive one.
  • The generator.next(value) method sends a value into a paused generator, which becomes the result of the yield expression.
  • The argument to the first next() call is always ignored.
  • This mechanism allows external code to control the internal state and flow of a generator.
  • This pattern of yielding promises and passing back resolved values is the conceptual foundation of async/await.

Next Up

We've seen how to create and control a single generator. But what if you want to compose them? In our next lesson, we will learn how to delegate iteration from one generator to another iterable or generator using the yield* expression, allowing you to build more complex and modular iteration logic.