Chapter XXIV · Advanced Concepts

Iterators

An iterator is an object that implements a `next()` method producing sequential items one by one, returning `{ value, done }`.

01 How It Works

Think of a cassette tape player stepping through tracks sequentially one movement at a time.

Iterators provide standard sequential traversal protocols across data structures like arrays, maps, and sets.

example.js
function makeIterator(array) {
  let index = 0;
  return {
    next() {
      return index < array.length 
        ? { value: array[index++], done: false }
        : { done: true };
    }
  };
}
const it = makeIterator(['a', 'b']);
console.log(it.next()); // { value: 'a', done: false }
  1. 1. Request an iterator object via `[Symbol.iterator]()`.

  2. 2. Call `.next()` repeatedly.

  3. 3. Inspect `{ value, done }` state return objects.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
const collection = [10, 20];
const iterator = collection[Symbol.iterator]();
console.log(iterator.next()); // { value: 10, done: false }

Key Takeaway

Iterators enable standardized sequential traversal across custom data structures.

Related Concepts