Course contentsShow
← JavaScript
Lesson 1026 of 2,72323. SymbolsFree lesson

Implementing Custom Iterators with Symbol.iterator

Making objects iterable by defining a Symbol.iterator method.

Implementing Custom Iterators with Symbol.iterator

You'll learn how to make your own objects work with for...of loops and spread operators by defining a custom iterator.

What's the Problem?

By default, plain objects aren't iterable—you can't use them in a for...of loop or spread them into arrays. JavaScript knows how to iterate over arrays and strings, but your custom objects are opaque boxes until you teach JavaScript how to iterate through them.

How Symbol.iterator Works

When JavaScript encounters a for...of loop or the spread operator, it looks for a method stored at the special Symbol.iterator key. This method should return an iterator object with a next() method that returns {value, done} objects.

Think of it like creating an instruction manual: you're telling JavaScript "here's how to walk through my object, one step at a time."

The Basic Pattern

const myIterable = {
  data: [10, 20, 30],
  [Symbol.iterator]() {
    let index = 0;
    const data = this.data;
    
    return {
      next() {
        if (index < data.length) {
          return { value: data[index++], done: false };
        }
        return { done: true };
      }
    };
  }
};

for (const num of myIterable) {
  console.log(num); // 10, 20, 30
}

const arr = [...myIterable]; // [10, 20, 30]

The Symbol.iterator method returns an object with a next() function. Each call to next() returns the next value and whether iteration is complete. Once done: true is returned, iteration stops.

Key Takeaway: By defining a Symbol.iterator method on your object, you unlock for...of loops, spread syntax, and other iteration protocols, giving you full control over how your object is traversed.