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

Symbol.iterator for Custom Iteration

Implement Symbol.iterator to make objects iterable with for...of loops and spread syntax.

Symbol.iterator for Custom Iteration

What you'll learn: How to make your own objects work with for...of loops and spread syntax by implementing Symbol.iterator.

Why Custom Iteration Matters

By default, only built-in iterables like arrays and strings work with for...of loops. But what if you want your custom object to be iterable too? That's where Symbol.iterator comes in—it's a special symbol that tells JavaScript how to iterate over your object.

How It Works

You add a method to your object using Symbol.iterator as the key. This method must return an iterator object with a next() method. Each call to next() should return an object with:

  • value: the current item
  • done: true when finished, false otherwise
const countdown = {
  from: 3,
  to: 1,
  [Symbol.iterator]() {
    let current = this.from;
    const end = this.to;
    return {
      next() {
        if (current >= end) {
          return { value: current--, done: false };
        }
        return { done: true };
      }
    };
  }
};

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

const arr = [...countdown];  // [3, 2, 1]

Think of It Like a Playlist

Imagine a music playlist. The Symbol.iterator method is like creating a remote control that knows how to play through your songs. The next() method says "give me the next track" until you reach the end.

Why This Matters

Once an object has Symbol.iterator, it unlocks:

  • for...of loops
  • Spread syntax (...)
  • Array destructuring
  • Any feature expecting an iterable

Key Takeaway: Implement Symbol.iterator to make any object iterable—it must return an iterator with a next() method that yields { value, done } objects.