Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

yield* and generator return values in JavaScript

84 yield*, and the value a generator returns

fair

Delegate from one generator into another with yield*, and catch the inner generator's return value as the value of the yield* expression. Show that spread never sees that value while next() does, delegate into a plain array and a string, bound an endless generator with a take helper, and stop one early with return().

Stuck? Three hints, smallest first
  1. 1. yield* inner() forwards every yield, and evaluates to whatever inner returned.
  2. 2. for...of and spread stop at done: true and throw the accompanying value away.
  3. 3. Never let for...of loose on an endless generator: take a fixed number and break.

The answer

function* rows(n) {
  for (let i = 1; i <= n; i++) yield `row ${i}`;
  return n;
}

function* block() {
  const counted = yield* rows(2);
  yield `counted ${counted}`;
  return 'block done';
}

const spreadSees = [...block()];
const stepped = [];
const it = block();
let step = it.next();
while (!step.done) {
  stepped.push(step.value);
  step = it.next();
}
const finalStep = [step.value, step.done];

function* mixed() {
  yield 'start';
  yield* ['garri', 'rice'];
  yield* 'NG';
  yield* rows(1);
}
const anyIterable = [...mixed()];

function* doubling(kobo) {
  let current = kobo;
  while (true) {
    yield current;
    current *= 2;
  }
}

const take = (n, iterable) => {
  const out = [];
  for (const value of iterable) {
    out.push(value);
    if (out.length === n) break;
  }
  return out;
};
const firstFive = take(5, doubling(100));

const stoppable = doubling(100);
const beforeStop = [stoppable.next().value, stoppable.next().value];
const stopped = stoppable.return('closed');
const afterStop = stoppable.next();

function* countingDown(from) {
  let n = from;
  while (n > 0) yield n--;
  return 'liftoff';
}
const inner = countingDown(3);
const outerValues = [...(function* () {
  const ending = yield* inner;
  yield ending;
})()];

console.log('spread :', spreadSees);
console.log('stepped:', stepped, '| final:', finalStep);
console.log('mixed  :', anyIterable);
console.log('endless:', firstFive, '| stop:', beforeStop, stopped, afterStop);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('yield* splices the inner sequence into the outer one', spreadSees, ['row 1', 'row 2', 'counted 2']);
test('so the inner return value arrives as the value of the yield* expression', spreadSees[2], 'counted 2');
test('stepping by hand sees the outer return value; spread never does', [stepped, finalStep], [['row 1', 'row 2', 'counted 2'], ['block done', true]]);
test('yield* works on any iterable, not only on generators', anyIterable, ['start', 'garri', 'rice', 'N', 'G', 'row 1']);
test('an endless generator is safe as long as the consumer stops', firstFive, [100, 200, 400, 800, 1600]);
test('return() ends a generator early and reports the value you gave it', [beforeStop, stopped], [[100, 200], { value: 'closed', done: true }]);
test('after that it is finished, and stays finished', afterStop, { value: undefined, done: true });
test('delegation carries the return value out through as many levels as you like', outerValues, [3, 2, 1, 'liftoff']);

yield* is delegation, not a loop: it forwards every value from the inner iterable, forwards next arguments inwards, forwards throw and return inwards too, and then evaluates to the inner generator's return value. That last part is the only clean way one generator can hand a summary back to its caller — a count, a total, a final cursor — while still having streamed the items one at a time.

Which is exactly what for...of and spread cannot see. They stop when done turns true and discard the value that came with it, so a generator whose answer is in its return looks like it produced nothing extra. If the summary matters, drive the iterator with next() yourself, or yield the summary as a final value like block does above.

Two safety notes. yield* accepts any iterable, so arrays, strings, Maps and other generators all splice in the same way. And an endless generator is only as safe as its consumer: [...doubling(100)] or a bare for...of over it never returns, so bound it with a take that breaks, and use return() when you want the producer to run its own cleanup.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.