The iterator protocol
Learn the next() method and the done/value structure.
The iterator protocol
An iterator is an object with a next() method. When you call next(), JavaScript returns a result object: { value, done }. value holds the current value, and done signals whether the iterator is exhausted.
This contract is the iterator protocol. Each call produces the next value; when the sequence ends, done: true comes back. JavaScript can then traverse any data structure the same way without knowing its internals.
done and value
While done is false, value is meaningful: it carries the current item. When done becomes true, the iterator is exhausted; value is usually undefined and ignored.
That is why loops check done first. When it is true, the loop exits. When you drive an iterator by hand, you must do the same check; otherwise an exhausted iterator keeps returning { value: undefined, done: true }.
Exercise Write a counter iterator
Create an object called counter. Its count property starts at 0. The next() method increments count by 1 on each call and returns { value, done }. For the first three calls return done: false; on the fourth return done: true. Then log the three values and the done flag of the fourth call with console.log.
Show example solution
const counter = {
count: 0,
next() {
this.count += 1;
if (this.count <= 3) {
return { value: this.count, done: false };
}
return { value: undefined, done: true };
}
};
console.log(counter.next().value);
console.log(counter.next().value);
console.log(counter.next().value);
console.log(counter.next().done);
Test yourself
-
What does an iterator's next() method return?
- A number
- An array
- A { value, done } object
- A function
Show answer
A { value, done } object — Correct. next() returns a result object.
-
Complete the next() result object
const iter = { count: 0, next() { this.count += 1; return { value: this.count, ____ }; } }; console.log(iter.next().done);Show answer
const iter = { count: 0, next() { this.count += 1; return { value: this.count, done: false }; } }; console.log(iter.next().done); -
Iterator protocol concepts
- next()
- Returns the next value
- value
- Holds the current value
- done
- Signals completion
- iterator
- Object with a next() method