0
0
JavascriptConceptBeginner · 3 min read

Iterable Protocol in JavaScript: What It Is and How It Works

The iterable protocol in JavaScript is a way objects can define how they are looped over using for...of loops or other iteration methods. An object is iterable if it has a Symbol.iterator method that returns an iterator, which produces values one at a time.
⚙️

How It Works

The iterable protocol lets JavaScript objects describe how to produce a sequence of values, one after another. Think of it like a playlist of songs: the playlist (the iterable) knows how to give you the next song when you ask for it.

To be iterable, an object must have a special method named Symbol.iterator. This method returns an iterator, which is like a helper that keeps track of where you are in the sequence and gives you the next value each time you ask.

This protocol allows JavaScript to use for...of loops, spread syntax, and other features on many types of objects, not just arrays.

💻

Example

This example shows a simple object that follows the iterable protocol by defining Symbol.iterator. It returns numbers from 1 to 3 one by one.

javascript
const myIterable = {
  [Symbol.iterator]() {
    let current = 1;
    const last = 3;
    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        } else {
          return { value: undefined, done: true };
        }
      }
    };
  }
};

for (const num of myIterable) {
  console.log(num);
}
Output
1 2 3
🎯

When to Use

Use the iterable protocol when you want to create custom objects that can be looped over easily with for...of or spread syntax. This is helpful when you have a collection or sequence that isn't a simple array but you want to provide a clean way to access its items one by one.

For example, you might create an iterable for a range of numbers, a stream of data, or a custom data structure like a tree or graph.

Key Points

  • An object is iterable if it has a Symbol.iterator method.
  • The Symbol.iterator method returns an iterator with a next() method.
  • The next() method returns an object with value and done properties.
  • Iterables work with for...of, spread syntax, and other iteration features.

Key Takeaways

The iterable protocol lets objects define how to be looped over using Symbol.iterator.
An iterator returned by Symbol.iterator produces values one at a time with next().
for...of loops and spread syntax work on any iterable object.
Custom iterables help create clean, reusable sequences beyond arrays.