Advertisement
Beginner JavaScript, Iterators & Generators

What makes an object 'iterable' in JavaScript?

Short 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.

Save JavaScript mock interview
Advertisement
AModel 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.
Likely follow-ups
  • Which built-in types are iterable by default in JavaScript?
Related topics