liveBook · Manning

Iterable

As explained in Secrets of the JavaScript Ninja, Third Edition

An iterable is an object that exposes an iteration protocol allowing its values to be traversed sequentially.

An iterable is an object whose Symbol.iterator method returns an iterator. That iterator’s next() method produces results with value and done properties, letting JavaScript retrieve values in sequence. section 8.3.1

You usually consume an iterable without calling next() yourself: for...of loops over its values, while destructuring and spread syntax retrieve or collect them. These operations use the iterator protocol under the hood, so arrays are one kind of iterable, not the only kind. section 8.3.1 section 8.3.1

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);

A custom iterable makes the protocol concrete: Symbol.iterator returns an object with next(), which supplies values as they are requested. section 8.3.1

An iterable need not be a stored, finite collection. It can generate values lazily; spreading or destructuring an infinite iterable can therefore keep requesting values without end. section 8.3.1

Generator functions provide a convenient way to create iterables. Each call to a generator’s next() advances execution to the next yield; the resulting generator object is both an iterable and an iterator. section 8.3.2 section 8.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains Symbol.iterator, next(), iterator results, custom iterables, lazy values, and generator behavior.
Examples
Uses array iteration, a custom random-number iterable, destructuring, spread, and an infinite generator.
What it assumes
Explains Symbol.iterator, next(), and iterator results directly, without naming prerequisite knowledge.
What you can do after
Build it from scratch by implementing Symbol.iterator and next(), then consume values with JavaScript iteration syntax.
How it connects
Connects iterables to iterators, generators, for...of loops, destructuring, spread syntax, and Symbol.iterator.

Also explained in

Compare how 8 books explain iterable →

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.