The return() method returns the given value and finishes the generator.
gen.return(value)
valueThe value that is given as an argument.
return()
The following example shows a simple generator and the return method.
function* gen() {
yield 1;
yield 2;
yield 3;
}
var 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 return 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;
}
var 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 }
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Generator.prototype.return' in that specification. | Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) The definition of 'Generator.prototype.return' in that specification. | Draft |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 50 | 13 | 38 | No | 37 | 10 |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | ? | 50 | 13 | 38 | Yes | 10 | 5.0 |
| Server | |
|---|---|
| Node.js | |
| Basic support | 6.0.0 |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return