Iterators and iterables: the for-of protocol
The loop for...of, the spread syntax, destructuring with an array pattern and Array.from all work on the same contract. The contract has two parts: an iterator is an object with a next method that returns { value, done }, and an iterable is an object with a method under the key Symbol.iterator that returns an iterator. Arrays, strings, maps and generators all implement it.
The protocol is small enough to write by hand, and doing that once makes every loop in the language readable. This lesson builds an iterator without any syntax, adds Symbol.iterator to make the same object work with for...of and the spread, shows why a generator can only be consumed once, and ends with a class whose instances are iterable.
The iterator protocol
An iterator keeps its position in a closure and returns one value per call. The object below counts to a limit: next returns the next number while there is one, and after that an object whose done is true. That is the whole protocol, with no classes and no syntax.
function makeCounter(limit) {
let current = 0;
return {
next() {
if (current < limit) {
current += 1;
return { value: current, done: false };
}
return { value: undefined, done: true };
},
};
}
const counter = makeCounter(3);
let step = counter.next();
console.log(`value=${step.value} done=${step.done}`);
step = counter.next();
console.log(`value=${step.value} done=${step.done}`);
step = counter.next();
console.log(`value=${step.value} done=${step.done}`);
step = counter.next();
console.log(`value=${step.value} done=${step.done}`);
try {
for (const value of counter) {
console.log(value);
}
} catch (error) {
console.log(error.name + ': ' + error.message);
}
node protocol.js
value=1 done=false
value=2 done=false
value=3 done=false
value=undefined done=true
TypeError: counter is not iterable
Four calls, three values and one finished flag. The error at the end is the other half of the contract: an iterator is not an iterable, and for...of does not call next on the object it is given, it looks for Symbol.iterator and calls that method to get the iterator. The message names the variable rather than the object, which is the hint a reader needs.
Symbol.iterator
The method under Symbol.iterator takes no arguments and returns an iterator. Each loop over the object calls it once, so a well-written iterable returns a fresh iterator every time and the loops do not interfere. The object below describes a range of numbers and is a few lines longer than the class in the last section and does the same job.
const range = {
from: 1,
to: 4,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
if (current <= last) {
const value = current;
current += 1;
return { value, done: false };
}
return { value: undefined, done: true };
},
};
},
};
console.log('spread:', [...range].join(','));
console.log('Array.from:', Array.from(range).length);
const seen = [];
for (const value of range) {
seen.push(value);
}
console.log('for...of:', seen.join(','));
const [first, second] = range;
console.log('destructured:', first, second);
node symbol.js
spread: 1,2,3,4
Array.from: 4
for...of: 1,2,3,4
destructured: 1 2
Four consumers, one method, four complete walks. The spread called Symbol.iterator and took everything until done, the loop asked for the same values one at a time, Array.from built an array from them, and the destructuring pattern took the first two and stopped asking. This is why the range printed its whole sequence four times: every consumer got its own iterator from a fresh call of the method.
An iterable and an iterator
An array is an iterable that can be walked again and again, and its iterator is a separate object that is used up. A generator is different: the generator object is the iterator and its own iterable at the same time, so it walks once and is then spent. The distinction matters as soon as a value is passed around.
const list = [1, 2, 3];
const iterator = list[Symbol.iterator]();
console.log('the list spreads twice:', [...list].join(','), 'and', [...list].join(','));
console.log('the iterator gives one value per call:', iterator.next().value, iterator.next().value);
console.log('after two steps the rest is:', [...iterator].join(','));
function* letters() {
yield 'a';
yield 'b';
}
const generator = letters();
console.log('a generator used once:', [...generator].join(','));
console.log('again:', JSON.stringify([...generator]));
console.log('a generator is both things:', typeof generator.next, typeof generator[Symbol.iterator]);
node oneshot.js
the list spreads twice: 1,2,3 and 1,2,3
the iterator gives one value per call: 1 2
after two steps the rest is: 3
a generator used once: a,b
again: []
a generator is both things: function function
The array gave each spread a new iterator, so both lines are complete. The iterator that was used twice continued from where it stood, and the spread picked up the remaining three. The generator, which is its own iterator, was empty on the second spread and the program printed an empty array rather than an error. A function that receives an iterable should say whether it walks it once or needs to walk it twice, and a generator argument can only be walked once.
A custom range
A class can implement the protocol just as an object literal can, and a generator method is the shortest way to write Symbol.iterator. The class below is a range that yields its numbers, and the second one is endless, so the caller decides how many values to take.
class Range {
constructor(from, to) {
this.from = from;
this.to = to;
}
*[Symbol.iterator]() {
for (let value = this.from; value <= this.to; value += 1) {
yield value;
}
}
}
const range = new Range(2, 5);
console.log([...range].join(','));
console.log('sum:', [...range].reduce((total, value) => total + value, 0));
class Fibonacci {
*[Symbol.iterator]() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
}
const first = [];
for (const value of new Fibonacci()) {
if (first.length === 8) {
break;
}
first.push(value);
}
console.log('fibonacci:', first.join(','));
node class.js
2,3,4,5
sum: 14
fibonacci: 0,1,1,2,3,5,8,13
The range was spread twice and summed the second time, because a class instance can make a new iterator for every walk. The Fibonacci class has no end, and the loop took eight values and left, which a method returning an array could not have offered. That is the practical value of the protocol: anything that can produce values one at a time becomes a loop, and the code that consumes it does not need to know whether the source is an array, a file or a calculation.
Exercises
- Give makeCounter in protocol.js a Symbol.iterator method that returns the object itself. Does the for...of loop work now, and what does it print?
- Change from of the range in symbol.js to 3 and to to 1. How many values do the four consumers see?
- Destructure three values from the range. What are they, and does the object keep a position of its own afterwards?
- Use the iterator of the list in oneshot.js a third time by hand and print the result. Which field tells the consumer that there is nothing left?
- Add a step field to the Range class and use it in the loop. Which values does new Range(0, 10) with a step of three produce?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What must an iterator have?
Answer
A next method that returns a value and a done flag
The protocol is one method with one shape of return value, and the consumers call it in a loop.
-
What must an iterable have?
Answer
A method under Symbol.iterator that returns an iterator
for...of and the spread look for that key, call it once and then use the iterator it returns.
-
What does this program print?
const it = [1, 2][Symbol.iterator](); console.log(it.next().value, it.next().value, it.next().done);Answer
1 2 true
The array iterator gives one value per call and reports done once the two items are used.
-
What does this program print?
const it = [1][Symbol.iterator](); console.log(typeof it.next, typeof it[Symbol.iterator]);Answer
function function
An array iterator is also iterable, and its Symbol.iterator method returns the iterator itself.
-
What does this program print?
const o = { [Symbol.iterator]() { let n = 0; return { next: () => (n < 2 ? { value: ++n, done: false } : { value: undefined, done: true }) }; } }; console.log([...o].join(","));Answer
1,2
The iterator counts up to two and the spread stops at the first done, so only the two yielded values arrive.
-
What does this program print?
try { for (const v of { a: 1 }) console.log(v); } catch (error) { console.log(error.name); }Answer
TypeError
A plain object has no Symbol.iterator method, so the loop throws before the first value.
-
Why can an array be spread twice but a generator only once?
Answer
Each spread of an array gets a new iterator, while a generator is its own used-up iterator
The array method returns a fresh iterator per call, and a generator object cannot rewind itself.
-
What does
Symbol.iteratorreturn when it is called on an iterable?Answer
A new iterator positioned before the first value
The method builds the object that does the walking, which is why each loop starts from the beginning.
-
What stops a
for...ofloop over an endless iterable?Answer
A break, or any other way of leaving the loop
The consumer decides when to stop asking, and a break leaves the loop without another call of next.
-
What is the shortest way to give a class the iteration protocol?
Answer
A generator method named with the Symbol.iterator key
A generator method already returns an iterator, so the star and the symbol key are the whole implementation.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev