🟨 JavaScript Intermediate

What are iterators and the iterable protocol?

Answer

An iterable is an object that implements Symbol.iterator — a method returning an iterator. An iterator is an object with a next() method that returns { value, done }. This protocol powers for...of, spread, destructuring, Array.from(), and Promise.all(). Built-in iterables: arrays, strings, Maps, Sets, generators, arguments. Custom iterable: const range = { from: 1, to: 5, [Symbol.iterator]() { let current = this.from; const last = this.to; return { next() { return current <= last ? { value: current++, done: false } : { value: undefined, done: true }; } }; } }; for (const n of range) console.log(n). An object can be both iterable AND an iterator (returns this from Symbol.iterator) — generators do this. Iterables enable lazy evaluation (process elements one at a time, not loading all into memory) and custom traversal logic.