The Iterator Object Contract
What You'll Learn
You'll learn the exact structure and behavior an iterator object must follow to work with JavaScript's iteration protocols.
The Iterator Object Specification
When you saw Symbol.iterator in the previous lesson, you learned that it returns an iterator object. But what exactly is an iterator object? JavaScript has a precise contract: an iterator must be an object with a next() method that follows specific rules.
The next() Method Contract
Every iterator object must provide a next() method that returns an object with two properties:
value: The current item in the sequencedone: A boolean indicating whether the iteration is complete
// A minimal iterator object
const simpleIterator = {
count: 0,
next() {
if (this.count < 3) {
return { value: this.count++, done: false };
}
return { value: undefined, done: true };
}
};
console.log(simpleIterator.next()); // { value: 0, done: false }
console.log(simpleIterator.next()); // { value: 1, done: false }
console.log(simpleIterator.next()); // { value: 2, done: false }
console.log(simpleIterator.next()); // { value: undefined, done: true }
The Done Signal
When done is true, iteration is complete. The value property at that point is typically undefined, though it can technically hold a final "return value." Once done becomes true, subsequent next() calls should keep returning done: true.
Think of It Like a Ticket Dispenser
Imagine a ticket machine at a deli counter. Each press of the button (calling next()) gives you a ticket with a number (value). When the roll runs out, you get a final message saying "no more tickets" (done: true).
Key Takeaway: An iterator object must have a next() method that returns {value, done}, where done: true signals the end of the sequence.