Sub topic 1
Why JavaScript Has Iteration Protocols
Prerequisites
This chapter assumes you know functions and arrow functions, objects and methods, the basics of arrays, Map, and Set, and spread syntax and destructuring.
One Contract for Many Collections
Before ES2015, each collection had its own way to loop over it. Arrays used index loops, objects used for...in, and DOM lists had their own methods. The iteration protocols replace this with a single contract. Any object that follows the contract works with for...of, spread, destructuring, and Array.from. Those features don't need to know what kind of collection they are reading.
Iterables and Symbol.iterator
An iterable is an object with a method stored under the key Symbol.iterator. When you call that method, it returns an iterator. Using a symbol as the key means the method can't clash with ordinary string property names.
Iterators, next(), and { value, done }
An iterator is an object with a next() method. Each call to next() returns a result object. The value field holds the current item, and the done field says whether the sequence has finished.
const letters = ['a', 'b'];
const it = letters[Symbol.iterator]();
console.log(it.next()); // { value: 'a', done: false }
console.log(it.next()); // { value: 'b', done: false }
console.log(it.next()); // { value: undefined, done: true }A for...of loop makes these same calls for you.
Built-in Iterables You Already Use
| Type | What it yields |
|---|---|
| Array, TypedArray | Elements in index order |
| String | Code points (not UTF-16 units) |
| Map | `[key, value]` pairs |
| Set | Values in insertion order |
| `arguments` | Arguments passed to the function |
Plain objects are not iterable. Use Object.entries(obj) when you need to loop over one.
What Consumes Iterables
const map = new Map([['x', 1], ['y', 2]]);
for (const [key, value] of map) {
console.log(key, value); // x 1, then y 2
}
const [first, ...rest] = 'hey';
console.log(first, rest); // h [ 'e', 'y' ]
console.log(Array.from(new Set([3, 3, 4]))); // [ 3, 4 ]Other consumers include new Map(iterable), new Set(iterable), Promise.all, and yield*.
Exercise
What does [...'ab'].length return, and which method does spread call first?
Show answer
It returns 2. Spread first calls 'ab'[Symbol.iterator](), then calls next() until done is true.
Exercise
Why does for (const x of { a: 1 }) throw an error while for (const x of new Map([['a', 1]])) works?
Show answer
A plain object has no Symbol.iterator method, so it is not iterable. Map defines one that yields [key, value] pairs.