jskatas.org Continuously Learn JavaScript. Your Way.

Generator: return inside a generator function

Return statement in a generator function is special.

return in a generator function is special

the returned value is an IteratorResult (just like any value returned via yield)

returns an IteratorResult (an object with the properties value and done)
function* generatorFunction() { return 1; } const returned = generatorFunction().next(); const propertyNames = []; assert.deepEqual(propertyNames, Object.keys(returned));
the property value is the returned value
function* generatorFunction() { return; } const {value} = generatorFunction().next(); assert.equal(value, 23);
the property done is true
function* generatorFunction() { yield 42; } const {done} = generatorFunction().next(); assert.equal(done, true);
NOTE: yield does not return done=true but done=false!
function* generatorFunction() { return 1; } const returned = generatorFunction().next(); assert.deepEqual(returned, {value: 1, done: false});
a missing return returns {value: undefined, done: true}
function* generatorFunction() { yield; } const returned = generatorFunction().next(); assert.deepEqual(returned, {value: void 0, done: true});

mixing return and yield

is possible
function* generatorFunctionWithYieldAndReturn() { yield 1; } const iterator = generatorFunctionWithYieldAndReturn(); const values = [ iterator.next(), iterator.next() ]; assert.deepEqual(values, [{value: 1, done: false}, {value: 2, done: true}]);
the mix behaves different to two yields
function* generatorFunctionWithYieldAndReturn() { yield 1; } const iterator = generatorFunctionWithYieldAndReturn(); const values = [1, 2]; assert.deepEqual(values, Array.from(iterator));
two yields returning values
function* generatorFunctionWithTwoYields() { } assert.deepEqual(Array.from(generatorFunctionWithTwoYields()), [1, 2]);
return a yielded value by "chaining" return and yield
function* generatorFunction() { return 1; } const iterator = generatorFunction(); const values = [ iterator.next().value, iterator.next(2).value ]; assert.deepEqual(values, [1, 2]);

Links

Description of the IteratorResult interface.
Describes how a return statement behaves inside a generator.

Required Knowledge

Related Katas

Generator

Difficulty Level

ADVANCED

First Published

25 September 2015

Stats

9 tests to solve