HomepageExploring JavaScript (ES2024 Edition)
You can support this book: buy it or donate
(Ad, please don’t block.)

32 Synchronous iteration [ES6]

32.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:

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.

Figure 32.1: Data consumers such as the for-of loop use the interface Iterable. Data sources such as Arrays implement that interface.

Figure 32.1 illustrates how iteration works: data consumers use the interface Iterable; data sources implement it.

Icon “details”The JavaScript way of implementing interfaces

In JavaScript, an object implements an interface if it has all the methods that it describes. The interfaces mentioned in this chapter only exist in the ECMAScript specification.

Both sources and consumers of data profit from this arrangement:

32.2 Core iteration constructs: iterables and iterators

Two roles (described by interfaces) form the core of iteration (figure 32.2):

Figure 32.2: Iteration has two main interfaces: Iterable and Iterator. The former has a method that returns the latter.

These are type definitions (in TypeScript’s notation) for the interfaces of the iteration protocol:

interface Iterable<T> {
  [Symbol.iterator]() : Iterator<T>;
}

interface Iterator<T> {
  next() : IteratorResult<T>;
}

interface IteratorResult<T> {
  value: T;
  done: boolean;
}

The interfaces are used as follows:

32.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 });

32.3.1 Iterating over an iterable via while

The following code demonstrates how to use a while loop to iterate over an iterable:

function logAll(iterable) {
  const iterator = iterable[Symbol.iterator]();
  while (true) {
    const {value, done} = iterator.next();
    if (done) break;
    console.log(value);
  }
}

logAll(['a', 'b']);

Output:

a
b

Icon “exercise”Exercise: Using sync iteration manually

exercises/sync-iteration/sync_iteration_manually_exrc.mjs

32.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.

32.4.1 Iterating over Arrays

JavaScript’s Arrays are iterable. That enables us to use the for-of loop:

const myArray = ['a', 'b', 'c'];

for (const x of myArray) {
  console.log(x);
}

Output:

a
b
c

Destructuring via Array patterns (explained later) also uses iteration under the hood:

const [first, second] = myArray;
assert.equal(first, 'a');
assert.equal(second, 'b');

32.4.2 Iterating over Sets

JavaScript’s Set data structure is iterable. That means for-of works:

const mySet = new Set().add('a').add('b').add('c');

for (const x of mySet) {
  console.log(x);
}

Output:

a
b
c

As does Array-destructuring:

const [first, second] = mySet;
assert.equal(first, 'a');
assert.equal(second, 'b');

32.5 Grouping iterables [ES2024]

Map.groupBy() groups the items of an iterable into Map entries whose keys are provided by a callback:

assert.deepEqual(
  Map.groupBy([0, -5, 3, -4, 8, 9], x => Math.sign(x)),
  new Map().set(0, [0]).set(-1, [-5,-4]).set(1, [3,8,9])
);

The items to be grouped can come from any iterable:

function* generateNumbers() {
  yield 2;
  yield -7;
  yield 4;
}
assert.deepEqual(
  Map.groupBy(generateNumbers(), x => Math.sign(x)),
  new Map().set(1, [2,4]).set(-1, [-7])
);

There is also Object.groupBy() which produces an object instead of a Map:

assert.deepEqual(
  Object.groupBy([0, -5, 3, -4, 8, 9], x => Math.sign(x)),
  {'0': [0], '-1': [-5,-4], '1': [3,8,9], __proto__: null}
);

32.5.1 Choosing between Map.groupBy() and Object.groupBy()

32.5.2 Example: handling cases

The Promise combinator Promise.allSettled() returns Arrays such as the following one:

const settled = [
  { status: 'rejected', reason: 'Jhon' },
  { status: 'fulfilled', value: 'Jane' },
  { status: 'fulfilled', value: 'John' },
  { status: 'rejected', reason: 'Jaen' },
  { status: 'rejected', reason: 'Jnoh' },
];

We can group the Array elements as follows:

const {fulfilled, rejected} = Object.groupBy(settled, x => x.status); // (A)

// Handle fulfilled results
assert.deepEqual(
  fulfilled,
  [
    { status: 'fulfilled', value: 'Jane' },
    { status: 'fulfilled', value: 'John' },
  ]
);

// Handle rejected results
assert.deepEqual(
  rejected,
  [
    { status: 'rejected', reason: 'Jhon' },
    { status: 'rejected', reason: 'Jaen' },
    { status: 'rejected', reason: 'Jnoh' },
  ]
);

For this use case, Object.groupBy() works better because we can use destructuring (line A).

32.6 Example: grouping by property value

In the next example, we’d like to group persons by country:

const persons = [
  { name: 'Louise', country: 'France' },
  { name: 'Felix', country: 'Germany' },
  { name: 'Ava', country: 'USA' },
  { name: 'Léo', country: 'France' },
  { name: 'Oliver', country: 'USA' },
  { name: 'Leni', country: 'Germany' },
];

assert.deepEqual(
  Map.groupBy(persons, (person) => person.country),
  new Map([
    [
      'France',
      [
        { name: 'Louise', country: 'France' },
        { name: 'Léo', country: 'France' },
      ]
    ],
    [
      'Germany',
      [
        { name: 'Felix', country: 'Germany' },
        { name: 'Leni', country: 'Germany' },
      ]
    ],
    [
      'USA',
      [
        { name: 'Ava', country: 'USA' },
        { name: 'Oliver', country: 'USA' },
      ]
    ],
  ])
);

For this use case, Map.groupBy() is a better choice because we can use arbitrary keys in Maps whereas in objects, keys are limited to strings and symbols.

32.7 Quick reference: synchronous iteration

32.7.1 Iterable data structures

The following built-in data structures are iterable:

To iterate over the properties of objects, we need helpers such as Object.keys() and Object.entries(). That is necessary because properties exist at a different level that is independent of the level of data structures.

32.7.2 Synchronously iterating language constructs

This section lists constructs that use synchronous iteration.

32.7.2.1 Language constructs that iterate
32.7.2.2 Turning iterables into data structures and Promises
32.7.2.3 Grouping an iterable into a Map or an object