Sub topic 3
Iterators, next(), and the { value, done } Result
The previous chapter showed that an iterable is any object with a Symbol.iterator method. This chapter covers what that method returns: an iterator, which is the object that actually hands out values one at a time. This chapter assumes you know functions and closures, objects and methods, and basic arrays. You do not need generators yet.
The iterator protocol in one sentence
An object is an iterator if it has a next() method that returns an iterator result object. The result object has two properties:
| Property | Meaning | If missing |
|---|---|---|
| `value` | The current item in the sequence | Treated as `undefined` |
| `done` | `false` while items remain, `true` once the sequence is finished | Treated as `false` |
That is the whole required contract. An iterator can also have optional return() and throw() methods. Later chapters cover those, starting with early exit and cleanup.
Stepping through an iterator by hand
for...of normally calls next() for you. You can do it yourself by asking an array for its iterator:
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 }Notice when done becomes true. It does not happen on the call that returns 'b', the last item. It happens on the call after that. An iterator does not know it is finished until something asks for one more value. Reading { value: 'b', done: false } as "last item, and finished" is a common off-by-one mistake.
The manual loop pattern
When you drive an iterator yourself, you usually write a while loop that checks done after each call:
const it = new Set(['x', 'y', 'z'])[Symbol.iterator]();
let result;
while (!(result = it.next()).done) {
console.log(result.value); // x, then y, then z
}This is close to what for...of does internally. It gets the iterator, calls next(), stops when done is truthy, and otherwise binds value to the loop variable. Writing the loop by hand is useful when you need to pull from two iterators in step, or consume a few items and then pass the rest of the iterator somewhere else.
Iterators are stateful and one-directional
An iterator remembers its position. Every call to next() moves it forward, and it cannot move back or reset. Getting a new iterator from the iterable starts again from the beginning:
const nums = [10, 20, 30];
const a = nums[Symbol.iterator]();
a.next(); // consumes 10
console.log([...a]); // [ 20, 30 ] (spread continues where a left off)
const b = nums[Symbol.iterator]();
console.log(b.next().value); // 10 (a fresh iterator starts over)Spreading a works because built-in iterators are also iterable: their Symbol.iterator method returns the iterator itself. That is why [...a] keeps going from the current position instead of starting over.
What done: true really means
The value is usually ignored
When done is true, the result can still carry a value. for...of, spread, destructuring, and Array.from all throw that value away. Only code that calls next() itself sees it. This becomes important with generators, where a return statement puts its value in the final done: true result.
A finished iterator should stay finished
Once an iterator has reported done: true, every later next() call should also report done: true. Built-in iterators follow this rule, even if the underlying collection changes afterwards:
const arr = [1];
const it = arr[Symbol.iterator]();
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: undefined, done: true }
arr.push(2);
console.log(it.next()); // { value: undefined, done: true } (still finished)Before the iterator finishes, though, an array iterator reads the array live by index. If you push an element in the middle of a for...of loop over an array, the loop will reach it. If you push on every pass, the loop never ends.
const queue = [1];
for (const n of queue) {
if (n < 3) queue.push(n + 1);
console.log(n); // 1, 2, 3
}Loose results and malformed results
Consumers check done for truthiness and read value as an ordinary property. The protocol therefore accepts loose results:
const loose = {
[Symbol.iterator]() {
let n = 0;
return {
next() {
// No done while running, no value at the end
return n < 2 ? { value: n++ } : { done: true };
}
};
}
};
console.log([...loose]); // [ 0, 1 ]It works, but write full { value, done } objects in your own code anyway. Readers and tools expect them.
The result itself must be an object. If next() returns a primitive such as 42 or undefined, the consumer throws a TypeError:
const broken = {
[Symbol.iterator]() {
return { next() { return 42; } };
}
};
try {
[...broken];
} catch (e) {
console.log(e instanceof TypeError); // true
}Two related failures throw the same error type. One is a Symbol.iterator method that returns something without a next method. The other is calling for...of on a plain object that has no Symbol.iterator at all.
Common errors
| Symptom | Likely cause |
|---|---|
| Loop body runs one time too few or too many | Treating the last `done: false` result as the end, or using `value` from the `done: true` result |
| Second loop over the same object produces nothing | Looping over an iterator, which is one-shot, instead of the iterable |
| `TypeError: ... is not an object` | `next()` returned a primitive or forgot to `return` |
| `TypeError: ... is not iterable` | The object has `next()` but no `Symbol.iterator`, so `for...of` cannot start |
| Infinite loop over an array | The loop body keeps pushing onto the array being iterated |
The last-but-one row is a common confusion. An object with only next() is an iterator but not an iterable. You can drive it by hand. for...of cannot use it until you add a Symbol.iterator method that returns it, which the next chapters do.
Exercise
Given const it = 'hi'[Symbol.iterator]();, what do four consecutive calls to it.next() return?
Show answer
{ value: 'h', done: false }, then { value: 'i', done: false }, then { value: undefined, done: true }, then { value: undefined, done: true } again, because a finished iterator stays finished.
Exercise
Write a function firstTwo(iterable) that uses next() directly, without for...of or spread, to return an array of at most the first two values. It must work for iterables with zero, one, or more items.
Show answer
function firstTwo(iterable) { const it = iterable[Symbol.iterator](); const out = []; while (out.length < 2) { const r = it.next(); if (r.done) break; out.push(r.value); } return out; } It checks done before using value, so short iterables never add undefined.
Exercise
An iterator's next() returns { value: 5, done: true } on its first call. What does [...iterable] produce, and why?
Show answer
An empty array []. Spread stops as soon as done is truthy and discards the value that comes with done: true.