Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Generator functions and yield in JavaScript

54 A first generator, and what yield gives back

fair

Write a function* that yields three stops and then returns a value. Prove that calling it runs none of the body, that each next() resumes where the last one stopped, and that the returned value is not one of the yielded ones.

Stuck? Three hints, smallest first
  1. 1. Calling a generator function builds a generator object and runs nothing. The body starts on the first next().
  2. 2. next() hands back { value, done }, and yield is where the body pauses.
  3. 3. A return value arrives on the result where done first becomes true, which is exactly the one spread and for...of throw away.

The answer

function* stops() {
  yield 'Oshodi';
  yield 'Ikeja';
  yield 'Agege';
  return 'depot';                             // not a yielded value
}

const log = [];
function* traced() {
  log.push('started');
  yield 1;
  log.push('resumed');
  yield 2;
  log.push('finished');
}

const it = traced();
const beforeAnyNext = [...log];               // still empty: nothing has run
const firstPull = it.next();
const afterFirst = [...log];
const secondPull = it.next();
const thirdPull = it.next();
const fourthPull = it.next();

const spread = [...stops()];
const viaForOf = [];
for (const stop of stops()) viaForOf.push(stop);

const g = stops();
g.next(); g.next(); g.next();
const withReturn = g.next();

const kinds = [typeof stops, typeof stops()];

console.log('before any next():', beforeAnyNext);
console.log('first pull       :', firstPull, '| log:', afterFirst);
console.log('second, third    :', secondPull, thirdPull);
console.log('log at the end   :', log);
console.log('spread           :', spread, '| return value:', withReturn);
console.log('typeof           :', kinds);

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('calling a generator function runs none of the body', beforeAnyNext, []);
test('the first next() runs as far as the first yield and stops', [firstPull, afterFirst], [{ value: 1, done: false }, ['started']]);
test('the next call resumes from there', secondPull, { value: 2, done: false });
test('when the body ends, done is true with no value, and pulling again is harmless', [thirdPull.done, thirdPull.value === undefined, fourthPull.done], [true, true, true]);
test('the body ran to the end exactly once', log, ['started', 'resumed', 'finished']);
test('spread and for...of both collect the yielded values', [spread, viaForOf], [['Oshodi', 'Ikeja', 'Agege'], ['Oshodi', 'Ikeja', 'Agege']]);
test('the returned value is not among them', spread.includes('depot'), false);
test('it arrives on the result that reports done', [withReturn.value, withReturn.done], ['depot', true]);
test('a generator function is a function; calling it gives an object', kinds, ['function', 'object']);

A generator is a function you can pause. The first assertion is the part that surprises people: traced() looks like a call but is closer to building a to-do list — no line of the body runs until something pulls. That laziness is the whole point, and it is what makes an endless sequence possible.

The return value is a trap worth remembering. It is real, and you can see it with a manual next(), but every consumer built on the iteration protocol — spread, for...of, destructuring, Array.from — stops as soon as done is true and discards the value that came with it. So return inside a generator is for ending it, not for producing a final item. If the value matters, yield it.

Newsletter

New writing, when it lands.

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