Passing Values to next()
What you'll learn: How to send data into a generator while it's paused, making generators truly interactive.
Two-Way Communication
So far, you've seen generators produce values using yield. But here's the powerful twist: you can also send values back into a generator by passing an argument to next().
When you call next(value), that value becomes the result of the yield expression that's currently paused. Think of it like a conversation where both sides can speak:
function* conversation() {
const response1 = yield "Hello, what's your name?";
console.log(`Nice to meet you, ${response1}!`);
const response2 = yield "How are you?";
console.log(`Glad you're ${response2}!`);
}
const gen = conversation();
console.log(gen.next().value); // "Hello, what's your name?"
console.log(gen.next("Alice").value); // Nice to meet you, Alice!
// "How are you?"
console.log(gen.next("great").value); // Glad you're great!
How It Works
- The first
next()starts the generator and runs until the firstyield - The second
next("Alice")resumes execution, and"Alice"becomes the value ofyield "Hello..." - That value gets stored in
response1
Important: The first next() call cannot pass a meaningful value (there's no yield waiting yet). Values passed to subsequent next() calls fill in the "blank" left by the previous yield.
Key Takeaway: Passing arguments to next() lets you inject values into a paused generator, turning yield into a two-way door for data flow.