Sub topic 1
Why JavaScript Has Iteration Protocols
Programs constantly walk through sequences of data: rows from a file, items in a cart, characters in a string. This chapter explains the problem that JavaScript's iteration protocols solve. The next chapters show how they work.
Prerequisites
This chapter assumes you are comfortable with:
- Functions, closures, and arrow functions
- Objects, classes, and methods
- Arrays,
Map, andSetbasics - Spread syntax and destructuring
The async chapters later in the tutorial also assume Promises and async/await.
The problem: every collection looped differently
Before ES2015, each kind of collection had its own way to loop over it. Arrays used index loops. Collection libraries shipped their own forEach or each methods. for...in walked over object keys, including inherited ones, and gave you keys rather than values.
const arr = [10, 20];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // 10, 20
}
const map = new Map([['a', 1]]);
map.forEach((value, key) => {
console.log(key, value); // a 1
});
const obj = { x: 1 };
for (const key in obj) {
console.log(key); // x (a key, not a value)
}Each style has a cost. Code that loops over data has to know what kind of collection it got. A callback-based forEach can't be stopped with break. A new data structure, such as a tree or a paginated API, needs its own looping API that no language feature understands.
The fix: one shared contract
ES2015 added two protocols. A protocol is an agreed set of methods that an object provides. Any object that follows the protocol can be used by any code that expects it.
- The iterable protocol describes an object that can hand out an iterator when asked.
- The iterator protocol describes an object that gives out values one at a time.
Data sources, called producers, implement these protocols. Language features, called consumers, rely on them. Neither side needs to know anything else about the other.
With the protocols in place, one loop form works on every built-in iterable:
for (const n of [10, 20]) console.log(n); // 10, 20
for (const ch of 'hi') console.log(ch); // h, i
for (const [k, v] of new Map([['a', 1]])) console.log(k, v); // a 1
for (const n of new Set([1, 2])) console.log(n); // 1, 2break, continue, and return all work inside these loops. A class you write yourself can join this list by implementing the protocol, and generators, covered later, make that short.
What the protocols also make possible
Because a consumer asks for one value at a time, a producer only has to compute the next value when it is asked for it. That property, called laziness, is what makes infinite sequences, streaming pipelines, and page-by-page API fetching possible. Later chapters build each of these.
Exercise
You have const scores = { alice: 9, bob: 7 };. Why does for (const s of scores) fail, and how would you loop over the name/score pairs with for...of?
Show answer
Plain objects do not implement the iterable protocol, so for...of throws a TypeError. Use for (const [name, score] of Object.entries(scores)). Object.entries returns an array of [key, value] pairs, and arrays are iterable.
Exercise
Give one practical advantage for...of has over Map.prototype.forEach.
Show answer
You can leave a for...of loop early with break or return. You can't stop forEach that way. Also, the same for...of code works on any iterable, so it doesn't depend on Map's own API.