Course contentsShow
← JavaScript
Lesson 1085 of 2,72325. Iterators and GeneratorsFree lesson

Implementing the Iterator Protocol

Learn the structure of a valid iterator: an object with a next() method that returns {value, done}.

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 sequence
  • done: 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 with value and done
  • When the sequence ends, done becomes true
  • Once done, the value property is optional (can be undefined)

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.