27. Synchronous iteration
27.1. What is synchronous iteration about?
Synchronous iteration is a protocol (interfaces plus rules for using them) that connects two groups of entities in JavaScript:
Data sources: On one hand, data comes in all shapes and sizes. In JavaScript’s standard library, you have the linear data structure Array, the ordered collection Set (elements are ordered by time of addition), the ordered dictionary Map (entries are ordered by time of addition), and more. In libraries, you may find tree-shaped data structures and more.
Data consumers: On the other hand, you have a whole class of mechanisms and algorithms that only need to access values sequentially: one at a time plus a way to tell when everything is done. Examples include the
for-of
loop and spreading into Array literals (via…
).
The iteration protocol connects these two groups via the interface Iterable
: data sources deliver their contents sequentially “through it”; data consumers get their input via it.
for-of
loop use the interface Iterable
. Data sources such as Arrays
implement that interface.The diagram in fig. 17 illustrates how iteration works: data consumers use the interface Iterable
; data sources implement it. Note that in JavaScript, implementing only means having the methods described by the interface; the interface itself only exists in the specification.
Both sources and consumers of data profit from this arrangement:
If you develop a new data structure, you only need to implement
Iterable
and a raft of tools can immediately be applied to it.If you write code that uses iteration, it automatically works with many sources of data.
27.2. Core iteration constructs: iterables and iterators
Two roles (described by interfaces) form the core of iteration (fig. 18):
- An iterable is an object whose contents can be traversed sequentially.
- An iterator is the pointer used for the traversal.
Figure 18: Iteration has two main interfaces: Iterable
andIterator
. The former has a method that returns the latter.
These are type definitions (in TypeScript’s notation) for the interfaces of the iteration protocol:
The interfaces are used as follows:
- You ask an
Iterable
for an iterator via the method whose key isSymbol.iterator
. - The
Iterator
returns the iterated values via its method.next()
. - The values are not returned directly, but wrapped in objects with two properties:
.value
is the iterated value..done
indicates if the end of the iteration has been reached, yet. It istrue
after the last iterated value andfalse
beforehand.
27.3. Iterating manually
This is an example of using the iteration protocol:
const iterable = ['a', 'b'];
// The iterable is a factory for iterators:
const iterator = iterable[Symbol.iterator]();
// Call .next() until .done is true:
assert.deepEqual(
iterator.next(), { value: 'a', done: false });
assert.deepEqual(
iterator.next(), { value: 'b', done: false });
assert.deepEqual(
iterator.next(), { value: undefined, done: true });
27.3.1. Iterating over an iterable via while
The following code demonstrates how to use a while
loop to iterate over an iterable:
27.4. Iteration in practice
We have seen how to use the iteration protocol manually and it is relatively cumbersome. But the protocol is not meant to be used directly – it is meant to be used via higher-level language constructs built on top of it. This section shows what that looks like.
27.4.1. Arrays
JavaScript’s Arrays are iterable. That enables you to use the for-of
loop:
Destructuring via Array patterns (explained later) also uses iteration, under the hood:
27.4.2. Sets
JavaScript’s Set data structure is iterable. That means, for-of
works:
As does Array-destructuring:
27.5. Quick reference: synchronous iteration
27.5.1. Iterable data sources
The following built-in data sources are iterable:
- Arrays
- Strings
- Maps
- Sets
- (Browsers: DOM data structures)
To iterate over the properties of objects, you need helpers such asObject.keys()
andObject.entries()
. That is necessary, because properties exist at a different level that is complementary to the level of data structures.
27.5.2. Iterating constructs
The following constructs support iteration:
- Destructuring via an Array pattern:
- The
for-of
loop:
Array.from()
:
- Spreading (via
…
) into Arrays and function calls:
new Map()
andnew Set()
:
Promise.all()
andPromise.race()
:
yield*
:
27.6. Further reading
For more details on synchronous iteration, consult “Exploring ES6”.