Sub topic 1
Why JavaScript Has Iteration Protocols
JavaScript code walks through sequences of data all the time: the items in an array, the characters in a string, the entries in a map, the rows coming back from an API. This chapter explains the problem the iteration protocols solve and why the language standardized one way to step through a sequence. Later chapters cover the mechanics in detail. Here the aim is the motivation behind the design, so the details that follow have a clear purpose.
Prerequisites
This chapter assumes you are comfortable with:
- Functions, closures, and arrow functions
- Objects, classes, and methods
- Arrays,
Map, andSetbasics - Spread syntax (
...) and destructuring
Promises and async/await are needed only for the async chapters near the end of the tutorial.
Life Before a Common Protocol
Before ES2015, there was no shared idea of "a thing you can loop over." Each kind of data came with its own way of looping, and each one had its own quirks.
Index loops only fit array-like data
A classic for loop works for anything with a length and numeric indexes. You have to manage the counter yourself, and the loop knows nothing about what it is walking through:
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}This pattern ties the consumer (the loop) to one detail of the producer (indexed storage). A linked list, a tree, or a stream of values computed on demand has no length and no indexes, so the loop cannot handle them.
for...in enumerates keys, not values
for...in looks like a general loop but it walks over an object's enumerable property names, including inherited ones. On arrays it gives string keys and picks up any extra properties:
const items = ['a', 'b'];
items.label = 'extra';
for (const key in items) {
console.log(key, typeof key);
}
// 0 string
// 1 string
// label stringThat is the right behavior for inspecting an object's properties. It is the wrong tool for visiting the values in a sequence.
forEach is a method, not a language feature
Array.prototype.forEach hides the counter. But each collection has to supply its own version, and you cannot stop it early with break. A return inside the callback only ends the current call:
[1, 2, 3, 4].forEach(n => {
if (n === 2) return; // skips 2, does not stop the loop
console.log(n);
});
// 1
// 3
// 4You also cannot await inside it in a way that pauses the loop, and you cannot write a function that accepts "anything with forEach" and trust that every such method behaves the same way.
Strings were split in the wrong places
Indexing a string reads UTF-16 code units. Characters outside the Basic Multilingual Plane, such as most emoji, take two code units, so index-based loops break them apart:
const s = 'hi😀';
for (let i = 0; i < s.length; i++) {
console.log(s[i]);
}
// h, i, then two broken halves of the emoji
for (const ch of s) {
console.log(ch);
}
// h, i, 😀The second loop uses the string's iterator, which steps by code point. The string itself decides what one "item" is, and that idea is the core of the protocol design.
The Many-to-Many Problem
Think of producers (arrays, strings, maps, sets, DOM node lists, your own classes) and consumers (loops, spread, destructuring, Array.from, Promise.all, the Map constructor). Without a shared contract, every consumer has to know how every producer stores its data. With N producers and M consumers, that is N × M special cases.
A protocol replaces those special cases with one agreement:
- A producer promises to hand out its values one at a time in a standard shape.
- A consumer promises to ask for values only through that shape.
Now each producer implements the contract once and each consumer understands it once. That is N + M pieces of work instead of N × M.
Here is that payoff in code. This one function works with any iterable, and it never checks what type it received:
function firstN(iterable, n) {
const out = [];
if (n <= 0) return out;
for (const x of iterable) {
out.push(x);
if (out.length >= n) break;
}
return out;
}
console.log(firstN([10, 20, 30], 2)); // [ 10, 20 ]
console.log(firstN('hi😀!', 3)); // [ 'h', 'i', '😀' ]
console.log(firstN(new Set(['x', 'y', 'z']), 2)); // [ 'x', 'y' ]
console.log(firstN(new Map([['k', 1], ['j', 2]]), 1)); // [ [ 'k', 1 ] ]Notice that break works here, unlike in forEach, and that the string is split by code point, unlike in an index loop.
Design Choices Behind the Protocols
The protocols you will meet in the next two chapters follow from a few deliberate decisions.
| Decision | What it means | Why it matters |
|---|---|---|
| Protocol, not base class | Any object with the right method qualifies (duck typing) | Existing and third-party types can join without inheriting from anything |
| Keyed by a well-known symbol | The method lives at `Symbol.iterator`, not a string name | No clash with existing properties named `iterator` or `next` on older objects |
| Pull-based | The consumer asks for the next value when it is ready | Values can be computed lazily, and sequences can be infinite |
| Stateful cursor separate from the data | Each pass gets its own cursor object | Two loops over the same array do not interfere |
| Optional early-exit hook | Consumers signal when they stop early | Producers holding files, sockets, or locks can clean up |
The pull-based design has the largest effect. Because the consumer controls the pace, a producer does not have to build the whole sequence up front. A sequence of all natural numbers is fine as long as the consumer stops asking. The same design later carries over to asynchronous data, where "ask for the next value" returns a promise instead.
What This Tutorial Builds On
The remaining chapters take these ideas apart in order. First comes the iterable protocol (the Symbol.iterator method) and the iterator protocol (the next() method and its { value, done } result). Then you will see the built-in iterables, the language features that consume them, and how to write your own iterables by hand. Generators come after that. They exist mostly because writing iterators by hand is repetitive, and they make lazy pipelines and async streams short to write.
Exercise
Given const a = [5, 6]; a.note = 'x';, what do for (const k in a) console.log(k) and for (const v of a) console.log(v) print, and why do they differ?
Show answer
The for...in loop prints the string keys "0", "1", and "note" because it enumerates enumerable property names. The for...of loop prints 5 and 6 because it uses the array's iterator, which yields only the array's element values.
Exercise
A codebase has 5 collection types and 4 places that loop over collections. Without a shared protocol, roughly how many type-specific looping cases might it need, and how many pieces of work does a protocol reduce this to?
Show answer
Up to 5 × 4 = 20 type-specific cases without a protocol. With a protocol, each collection implements it once and each consumer uses it once, so 5 + 4 = 9 pieces of work.
Exercise
Why can't you stop [1, 2, 3].forEach(...) partway through with break, while you can stop a for...of loop over the same array?
Show answer
forEach is an ordinary method that calls your callback once per element. break is not allowed inside the callback, and return only ends that one call. for...of is a language construct that pulls values from an iterator, so break stops the pulling and exits the loop.