jskatas.org Continuously Learn JavaScript. Your Way.

Generator: return inside a generator function

Return statement in a generator function is special.

Donate to NGO Julenka. Support Ukranians in need. Julenka is an NGO which my brother founded in 2011 to support Ukranian families and kids in need.

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)
  • the property value is the returned value
  • the property done is true
  • NOTE: yield does not return done=true but done=false!
  • a missing return returns {value: undefined, done: true}

mixing return and yield

  • is possible
  • the mix behaves different to two yields
  • two yields returning values
  • return a yielded value by "chaining" return and yield

Links

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