Course contentsShow
← JavaScript
Lesson 1117 of 2,72325. Iterators and GeneratorsFree lesson

Return Values from Delegated Generators

Capture the return value from a generator called with yield*.

Return Values from Delegated Generators

What you'll learn: How to capture and use the return value from a generator that you delegate to with yield*.

The Hidden Return Value

When you use yield* to delegate to another generator, you're not just forwarding all its yielded values — you can also capture what that generator returns when it's done. Remember, generators can use return to send a final value (separate from yielded values). The yield* expression itself evaluates to that return value.

Think of it like sending a messenger to deliver multiple packages (yields) and then bring back a final report (return value) when finished.

How It Works

When the delegated generator completes, the yield* expression produces the value from that generator's return statement:

function* innerGenerator() {
  yield 1;
  yield 2;
  return 'mission complete'; // This will be captured
}

function* outerGenerator() {
  const result = yield* innerGenerator();
  console.log('Inner returned:', result); // "mission complete"
  yield result;
}

const gen = outerGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
// Inner returned: mission complete
console.log(gen.next()); // { value: 'mission complete', done: false }

Notice that 'mission complete' doesn't appear as a yielded value from innerGenerator() itself — it's captured by the yield* expression and stored in result.

Why This Matters

This lets delegated generators communicate completion status or computed results back to the delegating generator, enabling sophisticated coordination patterns between generators.

Key Takeaway: The yield* expression evaluates to the return value of the delegated generator, letting you capture final results after all yields are exhausted.