Consuming Iterators with for...of
You'll learn: How the for...of loop automatically uses the iterator protocol to traverse collections.
The Automatic Iterator Consumer
You've already learned that arrays, strings, maps, and sets are iterables — they have a Symbol.iterator method that returns an iterator. But manually calling .next() repeatedly would be tedious. That's where for...of shines: it's syntactic sugar that automatically consumes iterators for you.
When you write a for...of loop, JavaScript does the following under the hood:
- Calls the
Symbol.iteratormethod on the collection to get an iterator - Repeatedly calls
.next()on that iterator - Extracts the
valuefrom each result object and assigns it to your loop variable - Stops when
donebecomestrue
How It Works
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// "red"
// "green"
// "blue"
This is equivalent to the manual approach:
const colors = ['red', 'green', 'blue'];
const iterator = colors[Symbol.iterator]();
let result = iterator.next();
while (!result.done) {
const color = result.value;
console.log(color);
result = iterator.next();
}
The for...of loop handles all the iterator mechanics automatically — you just work with the values.
Works With Any Iterable
const message = "hi";
for (const char of message) {
console.log(char); // "h", then "i"
}
const scores = new Set([10, 20, 30]);
for (const score of scores) {
console.log(score); // 10, 20, 30
}
Key Takeaway: for...of is a clean, readable way to consume any iterable — it automatically calls Symbol.iterator, loops through .next() results, and stops when iteration completes.