What does an iterator hand back each time you ask for another item? Calling next() returns an iteration result. Its value property carries the item produced on that step; its done property tells you whether iteration has finished. Keep the two together: value says what you got, while done says whether to keep asking. section 23.4
Watch a generator yield
For function* letters() { yield 'a'; yield 'b'; }, successive calls to letters().next() produce { value: 'a', done: false }, then { value: 'b', done: false }, then { value: undefined, done: true }. Each yield supplies an outgoing value and pauses execution. Reaching the end instead finishes the generator. If it explicitly returns a value, that final result can have done: true and a value other than undefined. section 18.2 section 18.1
Don’t confuse the value property with an argument passed to next(). A yielded value travels out in the result object; a later next(argument) can send a value back into the paused generator. The argument to the very first next() is not received by a yield, because that call only starts execution. section 18.2 section 18.1
function primesIterator () {
const primes = [2, 3, 5]
return {
next() {
const value = primes.shift()
const done = !value
return {
value,
done
}
}
}
}
This hand-written prime-number iterator takes an item from an array and returns it as value alongside done. Once the items are exhausted, done tells callers to stop. section 23.4
Try calling next() yourself on a generator that yields two values, then reaches its end. Check both properties after every call. When you use spread or for..of instead, they repeatedly request iterator results and stop when done becomes true. section 18.2 section 23.4
