The JavaScript Iterator Protocol: Building Custom Iterables
Iterables power for-of, spread, and destructuring. Here is how to implement the protocol and why you might. The iterator protocol is the contract that makes for-of loops, the spread operator, and array destructuring work. Any object that implements a specific method becomes iterable, and the language treats it uniformly across dozens of contexts. Understanding the protocol lets you build custom collections and lazy sequences that integrate smoothly with built-in syntax. The Two Protocols There are two related protocols. An iterable is an object with a method whose key is Symbol.iterator that returns an iterator. An iterator is an object with a next method that returns an object with value and done properties. When done is true, value is ignored and iteration stops. The for-of loop calls Symbol.iterator to get an iterator, then repeatedly calls next until done. const range = { from: 1, to: 3, [Symbol.iterator]() { let current = this.from; const last = this.to; return { next() { if (current <= last) { return { value: current++, done: false }; } return { value: undefined, done: true }; } }; } }; for (const n of…