Course contentsShow
← JavaScript
Lesson 1077 of 2,72325. Iterators and GeneratorsFree lesson

Consuming Iterators with for...of

How for...of loops work under the hood using the iterator protocol.

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:

  1. Calls the Symbol.iterator method on the collection to get an iterator
  2. Repeatedly calls .next() on that iterator
  3. Extracts the value from each result object and assigns it to your loop variable
  4. Stops when done becomes true

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.