An iterator is a small object that remembers traversal state and supplies the next value only when asked. This supports lazy data generation: callers can consume a few values without creating an entire collection first. section 8.3
The convention separates traversal from the data source:
- Symbol.iterator returns the iterator used by iteration. section 8.3
- next advances the state and returns a value together with a done flag. section 8.3
- for...of repeatedly requests values until iteration finishes. section 8.3
A stateful range iterator
function range(start, end) { return { [Symbol.iterator]() { return this; }, next() { return start < end ? { value: start++, done: false } : { value: end, done: true }; } }; } The incremented start variable preserves traversal state between calls. section 8.3
function range(start, end) {
return {
[Symbol.iterator]() { #1
return this;
},
next() {
if(start < end) {
return { value: start++, done:false }; #2
}
return { done: true, value:end }; #2
}
};
}
Inspect the complete range iterator implementation and its Symbol.iterator and next methods. section 8.3














