Implementing the Iterator Protocol
You'll learn how to create your own iterable object by defining a next() method that returns the correct structure.
What Makes an Iterator Valid?
To implement the iterator protocol, you need an object with a next() method that returns a special object with two properties:
value: the current item in the sequencedone: a boolean indicating whether iteration is complete (true) or not (false)
Think of it like a ticket dispenser: each time you call next(), it hands you a ticket (the value) and tells you whether there are more tickets left (done).
The Basic Structure
const myIterator = {
current: 1,
last: 3,
next() {
if (this.current <= this.last) {
return { value: this.current++, done: false };
} else {
return { done: true };
}
}
};
console.log(myIterator.next()); // { value: 1, done: false }
console.log(myIterator.next()); // { value: 2, done: false }
console.log(myIterator.next()); // { value: 3, done: false }
console.log(myIterator.next()); // { done: true }
Notice how:
- Each call to
next()returns an object withvalueanddone - When the sequence ends,
donebecomestrue - Once done, the
valueproperty is optional (can beundefined)
This is the core contract of the iterator protocol. Any object following this pattern is a valid iterator that JavaScript can work with.
Key Takeaway: A valid iterator is any object with a next() method that returns {value, done} — value holds the current item, and done signals completion.