JavaScriptFundamental (ES6), part 2
Iterator protocol: next(), done and value in JavaScript
1 The iterator result protocol, in full
fairWrite a generator that yields three values and then returns a fourth. Drive it with next() by hand and account for every result object, including the ones after it finishes. Then find out where the returned value went when you spread it.
Stuck? Three hints, smallest first
- 1. Every
next()gives back an object with exactly two properties,valueanddone. - 2. A
returnin the generator body arrives as the result whosedoneistrue. - 3.
for...ofand spread stop atdone: true, so they never see that value.
function* countdown(from) {
while (from > 0) yield from--;
return 'lift off';
}
const it = countdown(3);
const steps = [it.next(), it.next(), it.next(), it.next(), it.next()];
console.log('step by step:');
for (const s of steps) console.log(' ', JSON.stringify(s));
console.log('spread :', [...countdown(3)], '<- no "lift off"');
console.log('own iterator?', it[Symbol.iterator]() === it);
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.
test('the first next yields the first value', steps[0], { value: 3, done: false });
test('done stays false while values remain', steps.slice(0, 3).map((s) => s.done), [false, false, false]);
test('the returned value arrives with done true', steps[3], { value: 'lift off', done: true });
test('every next after that is done with no value', [steps[4].done, steps[4].value === undefined], [true, true]);
test('spread collects only the yielded values', [...countdown(3)], [3, 2, 1]);
test('so the returned value is invisible to it', [...countdown(3)].includes('lift off'), false);
test('a generator object is its own iterator', it[Symbol.iterator]() === it, true);
test('and it is one-shot: a spent one yields nothing', [...it], []);
The result object is the whole protocol. Two properties, value and done, and every consumer in the language — for...of, spread, destructuring, yield*, Promise.all over an iterable — is written against those two and nothing else.
The trap is the return value. It is delivered exactly once, alongside done: true, and every ordinary consumer stops when it sees done without reading value. So a return in a generator is only useful to code driving next() itself, or to a yield* that is expecting it. If you want a value in the output, yield it.
Being its own iterator is what makes a generator single-use. An array hands out a fresh iterator each time you loop it; a generator hands back this, and this remembers it is finished.