The Iterable Protocol

An object is iterable when it provides a method at Symbol.iterator that returns an iterator. The iterator provides a next() method returning objects shaped like { value, done }.

The for...of loop, spread syntax, array destructuring, and many collection APIs consume iterables. This is why custom objects can participate in standard iteration without being arrays.

Custom Iterable
const range = {
  start: 1,
  end: 3,
  *[Symbol.iterator]() {
    for (let value = this.start; value <= this.end; value++) {
      yield value;
    }
  }
};

console.log([...range]);
💡 The object defines Symbol.iterator using a generator, making it compatible with the iterable protocol.
Key Takeaways
  • Iterable objects expose Symbol.iterator.
  • Iterators expose next().
  • for...of consumes iterables rather than requiring arrays specifically.
Knowledge Check

Which symbol is used to define an object's default iteration behavior?