Lesson 7 of 9 · 21m
Iterables, Iterators, and the Spread Contract
The two-object iteration protocol behind `for...of`, destructuring, and spread — plus how to implement it without inventing ad-hoc collection APIs.
for...of, array spread, destructuring, Promise.all, and new Map(pairs) all rely on the same contract. An iterable has a Symbol.iterator method that returns an iterator. An iterator has a next() method returning { value, done }. Once you can see the contract, you can implement collection types that participate in the language instead of fighting it.
The protocol in one example
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const end = this.to;
return {
next() {
if (current <= end) {
return { value: current++, done: false };
}
return { value: undefined, done: true };
},
};
},
};
[...range]; // [1, 2, 3]The object itself is not iterated step by step. Calling range[Symbol.iterator]() produces the stateful iterator. That distinction lets one iterable produce independent iterations.
Iteration is pull-based
Consumers ask for the next value; producers do not push. That is why iteration composes so well with lazy sequences:
function* ids() {
let id = 0;
while (true) yield ++id;
}
const it = ids();
it.next().value; // 1
it.next().value; // 2No infinite array exists. The generator computes one item when asked. This is the design difference between elegant stream processing and accidental memory blowups.
Iterables can be consumed once or many times
Arrays are reusable iterables. Some objects — especially ones wrapping resources — are effectively single-use because Symbol.iterator returns the same iterator object:
const once = {
iterator: null,
[Symbol.iterator]() {
if (!this.iterator) this.iterator = makeNetworkIterator();
return this.iterator;
},
};If your API wraps I/O, document whether it is cold/reusable or hot/single-use. for...of cannot tell the user.
Early completion calls cleanup
When a consumer stops early — break, throw, or destructuring that does not consume everything — the iterator's return() method is called if present. Generators use this hook to run finally blocks. If you implement iterators over sockets, cursors, or file handles, implement return() for resource release.
Field notes
for...inenumerates property keys including inherited enumerable strings;for...ofiterates values through the iteration protocol. They are not interchangeable.Array.from(iterable, mapFn)is often clearer than spreading when you need transformation anyway.- Spreading a huge iterable copies it. Lazy code becomes eager at the spread boundary.
Object.entriesreturns an array of key/value pairs — not because objects are iterable by default, but because it builds one for you.
Was this lesson helpful?