liveBook · Manning

Iterator

As explained in Secrets of the JavaScript Ninja, Third Edition

An iterator is an object that advances through a sequence and reports each successive iteration result.

An iterator advances through values one at a time. Calling its next() method returns an iterator result with value and done properties. An iterable is the object that supplies an iterator through Symbol.iterator; the iterator is the object that supplies successive results. section 8.3.1

Listing 8.9 Looping through an array using its iterator
const numbers = [1, 2, 3];
const iterator = numbers[Symbol.iterator](); #A

let iteratorResult = iterator.next(); #B
while (!iteratorResult.done) { #C
  console.log(iteratorResult.value); #D
  iteratorResult = iterator.next(); #E
}

Calling an array’s iterator directly exposes the repeated next() calls that a for…of loop handles for you. section 8.3.1

Iterators also power destructuring and spread, so these operations can consume iterables beyond arrays. Maps provide iterators for entries, keys, and values. A generator object is both iterable and iterator: each next() call runs until yield or return, and yield pauses execution until the next call. section 8.3.1 section 8.3.2 section 10.2.2

Listing 8.10 Defining a custom iterable
const randomNumbers: Iterable<number> = { #A
  [Symbol.iterator]: () => ({ #B
    next: () => ({ value: Math.random() }), #B
  }), #B
};
 
const [num1, num2] = randomNumbers; #C
console.log(num1, num2);

This custom iterable uses Symbol.iterator to return an object with a next() method, illustrating the interface beyond built-in collections. section 8.3.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the iterable contract and iterator results, then traces next() through generator yield and return behavior.
Examples
Uses direct array iteration, a custom random-number iterable, generator delegation, and Map entry, key, and value loops.
What you can do after
Build it from scratch by defining Symbol.iterator to return an object with a next() method.
How it connects
Connects iterators to iterables, generators, destructuring, spread syntax, for…of, and Map.

Also explained in

Compare how 17 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.