Course contentsShow
← JavaScript
Lesson 2010 of 2,72342. Iteration Protocols Deep DiveFree lesson

Making Your Own Iterable Object

Implement [Symbol.iterator]() as a method that returns an iterator to make any object iterable.

Making Your Own Iterable Object

You'll learn how to transform any custom object into something that works with for...of loops and spread syntax by implementing the Symbol.iterator method.

The Core Idea

Remember from the last lesson that an iterator is an object with a next() method? Well, an iterable is an object that produces an iterator. To make any object iterable, you implement a special method using Symbol.iterator as the key. This method should return an iterator object.

Think of it like installing a "how to loop through me" instruction manual on your object. When JavaScript sees for...of or the spread operator, it looks for that manual (the Symbol.iterator method) and follows its instructions.

How It Works

You define a method on your object with the key Symbol.iterator. This method returns an iterator (an object with a next() method that returns {value, done} pairs).

const myRange = {
  start: 1,
  end: 3,
  
  [Symbol.iterator]() {
    let current = this.start;
    const last = this.end;
    
    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        }
        return { done: true };
      }
    };
  }
};

for (const num of myRange) {
  console.log(num);  // 1, 2, 3
}

console.log([...myRange]);  // [1, 2, 3]

Notice how [Symbol.iterator]() is a method that returns the iterator object. The iterator maintains its own state with current, and each call to next() advances through the values.

Key Takeaway: Any object becomes iterable when you add a [Symbol.iterator]() method that returns an iterator, unlocking for...of, spread syntax, and other iteration features.