Returning a final result
A generator performs a final calculation or reports a terminal status after yielding intermediate values.
JS Puzzles · Const
A generator's return(value) ends generator execution and supplies a final value. The caller sees it in the result of next() with done: true, unlike ordinary yielded values.
A generator can finish with return(value). That value is exposed by the next() result whose done property is true, unlike values produced by yield, which normally have done set to false. Calling generator.return(value) also ends a suspended generator and supplies that value in the result.
function* name() { return value; }
generator.return(value)| Name | Type | Description |
|---|---|---|
value | any | The value to expose as the generator's final result when return(value) completes execution. |
The final generator result is an object with value set to the returned value and done set to true.
function* count() {
yield 1;
return "finished";
}
const generator = count();
console.log(generator.next());
console.log(generator.next());The first call receives the yielded value; the second receives the generator's final return value with done set to true.
A generator performs a final calculation or reports a terminal status after yielding intermediate values.
A caller needs to stop a suspended generator early and communicate a value into its completion result.
Code manually drives a generator and must distinguish yielded items from its terminal value.
A generator's return value is delivered by the final next() call as the value property of an object with done: true. Values produced by yield are returned earlier, while the generator is still active.
Follow-up: What happens if next() is called after completion? It returns a completed iterator result, normally with done: true and value: undefined unless another completion behavior applies.
Use return(value) inside the generator to finish it and provide its final value. The caller observes that value through the next() result after the generator reaches completion.
Follow-up: How can the caller terminate a suspended generator? Call generator.return(value), which finishes execution and returns the supplied value in the iterator result.
yield pauses execution and sends a value outward, whereas return completes the generator. The next() result uses done: false for an active yielded value and done: true for the completed return value.
Follow-up: Why might a for...of loop not expose the return value? It consumes yielded values and stops when done becomes true, so the final completion value is not emitted as an iteration item.
function*yieldnext()iterableiterator