Skip to content

Commit 2275894

Browse files
authored
Merge pull request #2657 from Manik2375/generator.return
Add Generator.return
2 parents 16b9bda + 624b48b commit 2275894

File tree

1 file changed

+22
-0
lines changed
  • 1-js/12-generators-iterators/1-generators

1 file changed

+22
-0
lines changed

1-js/12-generators-iterators/1-generators/article.md

+22
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,28 @@ try {
448448

449449
If we don't catch the error there, then, as usual, it falls through to the outer calling code (if any) and, if uncaught, kills the script.
450450

451+
## generator.return
452+
453+
`generator.return(value)` finishes the generator execution and return the given `value`.
454+
455+
```js
456+
function* gen() {
457+
yield 1;
458+
yield 2;
459+
yield 3;
460+
}
461+
462+
const g = gen();
463+
464+
g.next(); // { value: 1, done: false }
465+
g.return('foo'); // { value: "foo", done: true }
466+
g.next(); // { value: undefined, done: true }
467+
```
468+
469+
If we again use `generator.return()` in a completed generator, it will return that value again ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return)).
470+
471+
Often we don't use it, as most of time we want to get all returning values, but it can be useful when we want to stop generator in a specific condition.
472+
451473
## Summary
452474

453475
- Generators are created by generator functions `function* f(…) {…}`.

0 commit comments

Comments
 (0)