Consume next results and completion
Quick answer
Iterator results separate a yielded value from completion. done tells the consumer whether the sequence has finished, so undefined is not a reliable end marker.
How it works
Call next once for each step, read done, and only then process value. If done is missing it behaves as false when the result is consumed. Iterators are generally stateful and consumption changes their position. For standard array iterators, once exhausted further calls remain done. A custom iterator should follow that convention. A completed generator can report a final return value, which ordinary for...of does not include.
const it=[undefined,0][Symbol.iterator](); const a=it.next(),b=it.next(),c=it.next(); console.log(a.done,b.value,c.done);Expected output in Node.js:
false 0 trueA yielded undefined is not completion.
const it=[1,2,3].values(); console.log(it.next().value,JSON.stringify([...it]),it.next().done);Expected output in Node.js:
1 [2,3] trueSpreading consumes only the remaining values.
Common mistakes
Do not stop at falsy values. Do not call next twice in a loop condition and body because that skips elements.
Practice
Manually consume an iterator over [0, undefined, false] using done as the only termination signal.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Consume next results and completion — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which field signals completion?
Can undefined be a yielded value?
After spreading a partially consumed array iterator, what remains?
What is the exact console output in Consume next results and completion example 1?
const it=[undefined,0][Symbol.iterator](); const a=it.next(),b=it.next(),c=it.next(); console.log(a.done,b.value,c.done);What is the exact console output in Consume next results and completion example 2?
const it=[1,2,3].values(); console.log(it.next().value,JSON.stringify([...it]),it.next().done);