The next() Method
What you'll learn: How to use the next() method to step through a generator function one yield at a time.
Resuming Generator Execution
When you call a generator function, it returns a generator object but doesn't run any code yet. The generator sits paused at the very beginning. To actually execute the generator's code, you call the next() method on that generator object.
Each time you invoke next(), the generator runs until it hits a yield keyword, then pauses again. The next() method returns an iterator result object with two properties: value (whatever was yielded) and done (a boolean indicating if the generator has finished).
Think of it like a video player's "play" button. Each press of next() plays the generator until the next pause point (yield), then stops and waits for you to press next() again.
How It Works
function* countToThree() {
yield 1;
yield 2;
yield 3;
}
const generator = countToThree();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
The first next() runs the generator from the start until the first yield 1. The second next() resumes from there until yield 2, and so on. Once the generator completes (no more yields), done becomes true and value is undefined.
Key Takeaway: The next() method is your remote control for generators—it resumes execution until the next yield, returning an object with the yielded value and completion status done.