Return in Generators
You'll learn how to end a generator early using return, which sets done to true and provides a final value.
The Core Idea
When you use a return statement inside a generator function, you're signaling that the generator is finished—even if there are more yield statements below. The return statement does two things: it sets the iterator's done property to true and allows you to specify one final value.
Think of a generator as reading pages from a book. Each yield is turning to a new page. Using return is like closing the book early—you get one last piece of information (the returned value) and then the book is officially closed.
How It Works
function* countdown() {
yield 3;
yield 2;
return 1; // Generator ends here
yield 0; // This never executes
}
const counter = countdown();
console.log(counter.next()); // { value: 3, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 1, done: true }
console.log(counter.next()); // { value: undefined, done: true }
Notice how the return value appears in the result object, but done is immediately true. Any code after return never executes—just like in regular functions.
Important Nuance with for...of
The for...of loop ignores the returned value:
for (let num of countdown()) {
console.log(num); // Logs: 3, 2 (but NOT 1)
}
The loop stops when done becomes true, and it doesn't capture that final returned value.
Key Takeaway: Using return in a generator ends iteration early with done: true and provides a final value, though that value is typically ignored by for...of loops.