Quiz
Warm-up from lesson 6-2: three independent fetches, and you need all three results. Which shape is fastest?
The iteration protocol
for...of works on arrays, strings, Maps, Sets, and even your own objects. How does it know how to walk them all? A shared contract with two halves:
- An iterator is any object with a
next()method returning{ value, done }. Each call hands over the next item, anddone: truemeans finished. - An iterable is any object that can produce an iterator, via a method stored under the special key
Symbol.iterator.
About that key: a symbol is a guaranteed-unique value used as a hidden property key. The language uses well-known symbols like Symbol.iterator so these hook methods can never collide with your normal property names.
The protocol exists to avoid an N×M explosion: the language has many consuming constructs (for...of, destructuring, the Map and Set constructors...) and many collection types. Instead of every construct knowing every type, they all speak { value, done }. Implement the contract once on your own class and all of those constructs work on it for free.
Code exercise · javascript
Run it. This is what for...of does for you: get the iterator, call next() until done is true.
Quiz
`for (const ch of "hi")` — what happens?
Quiz
Why does the language use `Symbol.iterator` as the key instead of a normal string like "iterator"?
Code exercise · javascript
Your turn. Make `countdown` iterable: implement `[Symbol.iterator]()` returning an iterator that yields 3, 2, 1. The for...of below should then just work.