Sub topic 14
Beyond Arrays: Strings, Sets, Maps, and Other Iterables
This chapter assumes you already know array destructuring and array spread from earlier chapters, and that you have used for...of loops. Array patterns and array spread work with any iterable, not only with arrays. An iterable is any object that has a Symbol.iterator method returning an iterator. That iterator hands out values one at a time.
How array patterns read values
When JavaScript evaluates const [a, b] = source, it does not use indexes. It calls source[Symbol.iterator](). Then it calls next() once for each position in the pattern. Array spread ([...source] or f(...source)) works the same way, except it keeps calling next() until the iterator reports done: true.
Strings, Sets, and Maps
Strings iterate by code point, Sets iterate by value, and Maps iterate by [key, value] entries.
const [c1, c2] = 'hi';
console.log(c1, c2); // 'h' 'i'
const unique = [...new Set([1, 1, 2, 3, 3])];
console.log(unique); // [1, 2, 3]
const scores = new Map([['ann', 90], ['bo', 75]]);
for (const [player, score] of scores) {
console.log(`${player}: ${score}`);
}
// ann: 90
// bo: 75Each Map entry is a two-element array, so a nested array pattern unpacks it. You can do the same thing outside a loop:
const scores = new Map([['ann', 90], ['bo', 75]]);
const [[firstName, firstScore]] = scores;
console.log(firstName, firstScore); // 'ann' 90
console.log([...scores.keys()]); // ['ann', 'bo']
console.log(Math.max(...scores.values())); // 90Because strings are iterated by code point, spread splits characters more accurately than length counts them:
const s = 'h😀';
console.log(s.length); // 3 (UTF-16 code units)
console.log([...s].length); // 2 (code points)Generators and laziness
A generator function returns an iterable iterator. Destructuring pulls only as many values as the pattern needs, so it is safe even with an infinite generator:
function* count() {
let n = 1;
while (true) yield n++;
}
const [one, two, three] = count();
console.log(one, two, three); // 1 2 3Plain objects are not iterable
A plain object has no Symbol.iterator, so array patterns and array spread reject it:
try {
const [x] = { a: 1 };
} catch (err) {
console.log(err instanceof TypeError); // true
}Object spread is a different mechanism. It copies own enumerable properties and never calls an iterator. Spreading a string into an object therefore produces index keys:
console.log({ ...'hi' }); // { 0: 'h', 1: 'i' }| Syntax | Uses the iterator? | Works on plain objects? |
|---|---|---|
| `[a, b] = x` | Yes | No (TypeError) |
| `[...x]`, `f(...x)` | Yes | No (TypeError) |
| `{ a } = x` | No | Yes |
| `{ ...x }` | No | Yes |
To iterate an object's data, convert it first with Object.entries(obj). That returns an array of [key, value] pairs, which you can destructure just like Map entries.
Exercise
What does this code log, and why? const m = new Map([['x', 1], ['y', 2]]); const [, [key, val]] = m; console.log(key, val);
Show answer
It logs 'y' 2. The Map iterator yields entries as [key, value] arrays. The empty slot skips the first entry, ['x', 1], and the nested pattern [key, val] unpacks the second entry, ['y', 2].
Exercise
Why does [...{ a: 1 }] throw while { ...{ a: 1 } } works?
Show answer
Array spread calls the value's Symbol.iterator method, and plain objects don't have one, so it throws a TypeError. Object spread copies own enumerable properties and doesn't use the iteration protocol, so it works on any object.