Writing an Iterator by Hand
An iterator is an object with a next method that returns value and done, and writing one makes the protocol concrete.
next() returns . for-of calls it repeatedly until done is true. Writing one by hand shows that iteration is pull-based: the consumer asks for each value, and nothing is computed until it does.
EXERCISE
1The next Method and Its Return Shape
Two properties on a returned object are the entire contract between a loop and whatever it is looping over.
Symbol.iterator returns an iterator. An iterator is any object with a next method that returns an object with two properties.
The shape:
// next() must return:
// { value: <the item>, done: false } there is more
// { value: undefined, done: true } finished
Driving one manually, which for-of does for you:
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 }
console.log(it.next()); // { value: undefined, done: true }
That is all for...of is doing: call next, use the value, stop when done is true. Notice the last two calls. Once an iterator is finished it keeps answering, and keeps answering the same thing, so a consumer that asks one time too many gets a clear signal rather than an error.
Written out, the loop is unremarkable:
const it = letters[Symbol.iterator]();
let result = it.next();
while (!result.done) {
console.log(result.value);
result = it.next();
}
A complete iterator with no arrays involved:
const countdown = {
from: 3,
[Symbol.iterator]() {
let current = this.from;
return {
next() {
if (current > 0) {
return { value: current--, done: false };
}
return { value: undefined, done: true };
},
};
},
};
console.log([...countdown]); // [ 3, 2, 1 ]
Note where current lives: inside Symbol.iterator, not on the object. That matters, and the next exercise shows why.
And this is why iteration is lazy:
const naturals = {
[Symbol.iterator]() {
let n = 0;
return {
next() {
return { value: n++, done: false }; // never done
},
};
},
};
for (const n of naturals) {
if (n > 4) break;
console.log(n); // 0 1 2 3 4
}
An infinite sequence, and the loop terminates. Nothing was precomputed. Each value was produced only when the loop asked for it, which is what "pull-based" means and is impossible with an array.
Pro Tip:
{ value, done }is worth committing to memory, because it is the whole protocol. Anything with anextreturning that shape can be iterated, which means you can wrap a paginated API, a file being read line by line, or a stream of events in exactly the syntax people already use for arrays.
EXERCISE
2State, and Why Each Loop Needs Its Own
Where you put the counter decides whether your object can be iterated twice, and getting it wrong is a real bug.
The bug: state on the object itself.
const broken = {
from: 3,
current: 3,
[Symbol.iterator]() {
const self = this;
return {
next() {
if (self.current > 0) {
return { value: self.current--, done: false };
}
return { value: undefined, done: true };
},
};
},
};
console.log([...broken]); // [ 3, 2, 1 ]
console.log([...broken]); // [] <- exhausted
The second spread gets nothing. current reached zero during the first and was never reset, because it lives on the shared object.
The fix: state inside Symbol.iterator.
const working = {
from: 3,
[Symbol.iterator]() {
let current = this.from; // fresh on every call
return {
next() {
if (current > 0) {
return { value: current--, done: false };
}
return { value: undefined, done: true };
},
};
},
};
console.log([...working]); // [ 3, 2, 1 ]
console.log([...working]); // [ 3, 2, 1 ]
Each call to Symbol.iterator creates a new current in a new closure. Two loops over the same object get independent iterators and do not interfere. This is the closure behaviour from the foundations course doing real work: the variable outlives the function call that created it, and each call gets its own.
Which is exactly how arrays behave, and why it feels natural:
const arr = [1, 2, 3];
const a = arr[Symbol.iterator]();
const b = arr[Symbol.iterator]();
console.log(a.next().value); // 1
console.log(b.next().value); // 1, independent
An iterator that is also iterable is a deliberate exception:
function makeIterator(items) {
let i = 0;
return {
next() {
return i < items.length
? { value: items[i++], done: false }
: { value: undefined, done: true };
},
[Symbol.iterator]() {
return this; // return itself, not a fresh one
},
};
}
const it = makeIterator(["a", "b", "c"]);
console.log(it.next().value); // a
console.log([...it]); // [ 'b', 'c' ] <- continues, does not restart
Returning this makes it single-use on purpose, so a for...of can be paused with break and resumed later. Generators do exactly this, which is why a half-consumed generator continues where it left off rather than starting again.
The distinction, stated plainly:
// Iterable has Symbol.iterator, usually returns a FRESH iterator
// Iterator has next(), holds position, is consumed once
//
// An array is iterable and can be looped forever.
// A generator is both, and can be looped once.
Pro Tip: If your object should be loopable more than once, create the state inside
Symbol.iterator. If it represents a one-time stream, such as reading a file or draining a queue, returningthisand being consumed once is honest and prevents a caller assuming they can replay it.
EXERCISE
3Wrapping a Real Source
The protocol earns its place when the values come from somewhere that is not already an array.
Everything so far iterated over data that was already in memory. The reason to learn the protocol is the case where it is not.
A paginated source, consumed one item at a time:
function paginated(pages) {
return {
[Symbol.iterator]() {
let pageIndex = 0;
let itemIndex = 0;
return {
next() {
while (pageIndex < pages.length) {
const page = pages[pageIndex];
if (itemIndex < page.length) {
return { value: page[itemIndex++], done: false };
}
pageIndex += 1;
itemIndex = 0;
}
return { value: undefined, done: true };
},
};
},
};
}
const source = paginated([["a", "b"], ["c"], ["d", "e"]]);
console.log([...source]); // [ 'a', 'b', 'c', 'd', 'e' ]
The consumer sees a flat sequence. The page boundaries are an implementation detail they never encounter.
The same thing as a generator, for comparison:
function* paginated(pages) {
for (const page of pages) {
yield* page;
}
}
Two lines against twenty. Lesson 3 explains why, and this side-by-side is the argument for reading generators as the normal way to write an iterator.
A source with a real cost per item:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function* take(iterable, count) {
let taken = 0;
for (const value of iterable) {
if (taken >= count) return;
yield value;
taken += 1;
}
}
console.log([...take(fibonacci(), 8)]);
// [ 0, 1, 1, 2, 3, 5, 8, 13 ]
fibonacci is infinite and take stops it. Neither knows about the other. This composes because both sides speak the same protocol, and it is the shape that libraries like Lodash's lazy chains and Python's itertools are built on.
And the practical version of that idea:
function* filter(iterable, predicate) {
for (const value of iterable) {
if (predicate(value)) {
yield value;
}
}
}
function* map(iterable, fn) {
for (const value of iterable) {
yield fn(value);
}
}
const result = take(map(filter(fibonacci(), (n) => n % 2 === 0), (n) => n * 10), 4);
console.log([...result]); // [ 0, 20, 80, 340 ]
Nothing is computed until the final spread pulls on it, and only as many values as were needed are produced. The array equivalent would have to build a complete intermediate array at each step, which is impossible here because the source never ends.
Pro Tip: The protocol is worth the effort precisely when an array is not an option: an infinite sequence, a source too large for memory, or values that cost something to produce. For a list you already hold, array methods are clearer and you should use them. Reach for iteration when laziness is the point.
