JavaScript › Iterators & Generators

What makes an object 'iterable' in JavaScript?

Beginner

Answer

An object is iterable if it implements the Symbol.iterator method, which returns an iterator object with a next() method. This is what powers for...of loops, spread syntax, and destructuring on that object.
const range = {
  [Symbol.iterator]() {
    let i = 1;
    return { next: () => i <= 3 ? { value: i++, done: false } : { value: undefined, done: true } };
  }
};
console.log([...range]); // [1, 2, 3]
Real-world example Making a custom collection class work seamlessly with for...of and spread, just like a built-in Array.

Common follow-ups: Which built-in types are iterable by default in JavaScript?