The return(value) method

You can end a generator function any time before it has yielded all the values by using the return() method of the generator object. The return() method takes an optional argument, representing the final value to return.

Here is an example demonstrating this:

function* generator_function(){  yield 1;  yield 2;  yield 3;}const generator = generator_function();console.log(generator.next().value);console.log(generator.return(22).value);console.log(generator.next().done);

The output is as follows:

122true

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.