What is iterator protocol?
The iterator protocol is a contract: an iterator is any object with a next() method returning { value, done }; an object is iterable when its [Symbol.iterator]() method returns such an iterator, which lets it work with for...of, spread, destructuring, Array.from, Promise.all and more.
The two protocols
- Iterable: has
[Symbol.iterator](), which returns a fresh iterator. - Iterator: has
next(), returning{ value: any, done: boolean }. Optionallyreturn()(called on early exit likebreak, so you can clean up) andthrow().
Built-in iterables
Arrays, strings (by code point), Map, Set, arguments, typed arrays, NodeList, generator objects, and the results of map.entries(), array.keys() and so on. Plain objects are not iterable; use Object.entries(obj).
What consumes iterables
for...of, spread ([...x]), array destructuring, Array.from, new Map(iterable), new Set(iterable), Promise.all/race/allSettled/any, yield*, and Object.fromEntries.
Writing your own
The easiest way is a generator method: *[Symbol.iterator]() { ... }. Writing next() by hand is useful to understand the protocol and when you need precise control.
Iterators are single-use
An iterator is consumed once. An iterable can usually produce many iterators (each for...of calls [Symbol.iterator]() again). Generator objects are both iterable and iterator, so they are single-use too.
Lazy evaluation
Iterators compute values on demand, which enables infinite sequences and memory-friendly processing of large data.
Code example
1// Hand-written iterator: implementing the protocol directly2class Range {3 constructor(start, end, step = 1) {4 Object.assign(this, { start, end, step });5 }6 [Symbol.iterator]() {7 let current = this.start;8 const { end, step } = this;9 return {10 next: () => (current <= end ? { value: (current += step) - step, done: false } : { value: undefined, done: true }),11 return: () => {12 console.log("iterator closed early");13 return { done: true };14 },15 };16 }17}1819const r = new Range(1, 10, 3);20console.log([...r]); // [1, 4, 7, 10]21const [first, second] = r; // destructuring stops early -> return() is called22console.log(first, second); // 1 42324// The protocol step by step25const it = ["a", "b"][Symbol.iterator]();26console.log(it.next(), it.next(), it.next()); // { value: "a", done: false } { value: "b", done: false } { value: undefined, done: true }2728// Everything that accepts iterables works with our class29console.log(Math.max(...new Range(1, 5)), new Set(new Range(1, 3)).size); // 5 33031// Plain objects are not iterable - use Object.entries32const scores = { ada: 9, linus: 7 };33for (const [name, score] of Object.entries(scores)) console.log(name, score);34console.log(typeof scores[Symbol.iterator]); // undefined
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.