Course contentsShow
← JavaScript
Lesson 1110 of 2,72325. Iterators and GeneratorsFree lesson

Passing Values into Generators with next()

Understand how arguments to next() become the result of the yield expression.

Passing Values into Generators with next()

You'll learn how to send data back into a paused generator, making it a two-way communication channel.

The Two-Way Street

So far, you've seen generators yield values out to the caller. But here's the magic: when you call next(value) with an argument, that value becomes the result of the yield expression where the generator is paused. The generator receives whatever you pass in!

Think of it like a conversation where someone pauses mid-sentence. When they resume, you can hand them a note — and they'll continue their sentence using what you wrote.

How It Works

function* dialogue() {
  const name = yield "What's your name?";
  console.log(`Hello, ${name}!`);
  
  const color = yield "What's your favorite color?";
  console.log(`${color} is nice!`);
}

const chat = dialogue();

console.log(chat.next().value);        // "What's your name?"
console.log(chat.next("Alice").value); // Logs "Hello, Alice!"
                                        // Returns "What's your favorite color?"
console.log(chat.next("blue").value);  // Logs "blue is nice!"
                                        // Returns undefined

The first next() starts the generator and runs until the first yield. The second next("Alice") sends "Alice" back, which becomes the value of const name = yield ..., then runs until the next yield.

Important: The first next() call can't pass a meaningful value because there's no yield waiting to receive it yet.

Key Takeaway: Arguments passed to next() become the result of the yield expression where the generator last paused, enabling two-way data flow between generator and caller.