The return()
method returns the given value and finishes the generator.
Syntax
gen.return(value)
Parameters
value
- The value to return.
Return value
The value that is given as an argument.
Examples
Using return()
The following example shows a simple generator and the return
method.
function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true }
If return(value)
is called on a generator that is already in "completed" state, the generator will remain in "completed" state.
If no argument is provided, the value
property of returned object is the same as if .next()
. If an argument is provided, it will be set to the value of the value
property of the returned object.
function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } g.return(); // { value: undefined, done: true } g.return(1); // { value: 1, done: true }
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Generator.prototype.return' in that specification. |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
return | Chrome Full support 50 | Edge Full support 13 | Firefox Full support 38 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 38 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
Legend
- Full support
- Full support
- No support
- No support