Sub topic 14
Beyond Arrays: Strings, Sets, Maps, and Other Iterables
Array destructuring and array spread look like they are tied to arrays, but they are not. Both are defined in terms of the iteration protocol, so they work with any value that can be iterated. That includes strings, Sets, Maps, generator results, and objects you write yourself. This chapter covers how that works, how it behaves with each built-in iterable, and where it breaks.
This chapter assumes you know basic array destructuring, rest elements, and array spread from earlier chapters. You should also be comfortable with for...of loops. Generators (function*) appear in some examples. You only need to know that yield hands out one value at a time.
The iteration protocol in one paragraph
A value is iterable if it has a method under the key Symbol.iterator. Calling that method returns an iterator, which is an object with a next() method. Each call to next() returns { value, done }. Array destructuring, array spread, for...of, Array.from, and new Set(...) / new Map(...) all consume values this way. They never check whether the source is an array. They only ask for its iterator.
Strings
Strings are iterable, and they iterate by code point, not by UTF-16 code unit. This matters for emoji and other characters outside the Basic Multilingual Plane.
const greeting = '👋hi';
console.log(greeting.length); // 4 (UTF-16 code units)
console.log(greeting.split('').length); // 4 (splits the emoji into two halves)
console.log([...greeting].length); // 3 (code points)
const [first, ...restChars] = greeting;
console.log(first); // '👋'
console.log(restChars); // ['h', 'i']Use [...str] when you need user-visible characters to stay intact. It is still not a full grapheme splitter. Combined emoji such as family sequences and flag pairs are made of several code points, and spread separates them. For true graphemes, use Intl.Segmenter.
Strings also work with object destructuring, because the string is boxed into a String object and its properties are read:
const { length, 0: initial } = 'hello';
console.log(length); // 5
console.log(initial); // 'h'Sets
A Set iterates over its values in insertion order. Spread is the usual way to turn a Set back into an array, and deduplicating with it is a common idiom.
const tags = new Set(['js', 'css', 'js', 'html']);
const [firstTag, secondTag] = tags;
console.log(firstTag, secondTag); // 'js' 'css'
const tagList = [...tags];
console.log(tagList); // ['js', 'css', 'html']
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const intersection = [...a].filter((n) => b.has(n));
const union = new Set([...a, ...b]);
console.log(intersection); // [2, 3]
console.log([...union]); // [1, 2, 3, 4]Sets have no indexes, so destructuring is the simplest way to get "the first value" without writing a loop.
Maps
A Map's default iterator yields entries, and each entry is a two-element array [key, value]. Every Map example that uses destructuring depends on this shape, so you end up writing nested array patterns.
const scores = new Map([
['ann', 90],
['bo', 75],
['cy', 82],
]);
// Destructure each entry in a loop
for (const [player, score] of scores) {
console.log(`${player}: ${score}`);
}
// Take the first entry, then split it
const [[topName, topScore]] = scores;
console.log(topName, topScore); // 'ann' 90
// Spread to an array of pairs, transform, rebuild
const passed = new Map([...scores].filter(([, score]) => score >= 80));
console.log([...passed.keys()]); // ['ann', 'cy']
// keys(), values(), entries() are iterables too
const total = [...scores.values()].reduce((sum, n) => sum + n, 0);
console.log(total); // 247In ([, score]) => ..., the empty slot skips the key. This is the usual way to ignore one half of an entry.
Plain objects are not iterable, but Object.entries returns an array in the same [key, value] shape. As a result, the same patterns work for objects too:
const prices = { tea: 3, cake: 5 };
for (const [item, price] of Object.entries(prices)) {
console.log(item, price);
}
const asMap = new Map(Object.entries(prices));
console.log(asMap.get('cake')); // 5Generators and laziness
A destructuring pattern pulls only as many values as it needs. When it has enough and the iterator is not finished, it calls the iterator's return() method to close it. For generators, closing runs any finally block.
function* counter() {
try {
let i = 1;
while (true) {
console.log('yield', i);
yield i++;
}
} finally {
console.log('closed');
}
}
const [x, y] = counter();
// yield 1
// yield 2
// closed
console.log(x, y); // 1 2The generator is infinite, but the pattern [x, y] stops after two values. A rest element or spread works differently: it pulls values until done is true.
Writing your own iterable
Any object with a Symbol.iterator method works with spread and array patterns. A generator method is the shortest way to write one:
const range = {
from: 1,
to: 5,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
},
};
console.log([...range]); // [1, 2, 3, 4, 5]
console.log(Math.max(...range)); // 5
const [low, , mid] = range;
console.log(low, mid); // 1 3Each spread or destructuring calls Symbol.iterator again, so range can be consumed many times. An iterator that returns itself from Symbol.iterator behaves differently. Generator objects are the common example, and they can be used only once:
const gen = range[Symbol.iterator]();
console.log([...gen]); // [1, 2, 3, 4, 5]
console.log([...gen]); // [] (already exhausted)Where it fails: array-likes and plain objects
An array-like has a length and numeric keys but no Symbol.iterator. A plain object built that way is not iterable. In older code, the arguments object of non-arrow functions was the classic array-like, but modern engines give it an iterator. Array-likes you build yourself still fail:
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
try {
const [p] = arrayLike;
} catch (err) {
console.log(err instanceof TypeError); // true ("is not iterable")
}
console.log(Array.from(arrayLike)); // ['a', 'b'] (Array.from accepts array-likes)Array.from checks for an iterator first and then falls back to length. Spread has no fallback.
Object spread does not use iteration
Object spread copies own enumerable properties. It never calls Symbol.iterator. When the source is iterable, this gives results that can surprise you:
console.log({ ...'hi' }); // { 0: 'h', 1: 'i' }
console.log({ ...new Set([1, 2]) }); // {} (Set values are not properties)
console.log({ ...new Map([['k', 1]]) }); // {}
console.log(Object.fromEntries(new Map([['k', 1]]))); // { k: 1 }Use Object.fromEntries to turn a Map, or any iterable of pairs, into an object.
Summary table
| Source | `[...x]` / `const [a] = x` | `{...x}` | Notes |
|---|---|---|---|
| Array | Elements | Index keys | Holes become `undefined` with array spread |
| String | Code points | Index keys (code units) | Emoji stay whole with array spread |
| Set | Values in insertion order | `{}` | Use spread to deduplicate |
| Map | `[key, value]` entries | `{}` | Use `Object.fromEntries` for an object |
| Generator | Yielded values, once | `{}` | Rest/spread never ends on infinite generators |
| Plain object | TypeError | Own enumerable props | Use `Object.entries` to iterate |
| Array-like | TypeError | Index keys and `length` | Use `Array.from` |
Exercise
Given const m = new Map([['x', 1], ['y', 2], ['z', 3]]);, write one statement that declares secondKey as 'y' using destructuring only, and a second statement that builds a plain object containing only the entries whose value is odd.
Show answer
const [, [secondKey]] = m; skips the first entry, then destructures the second entry's key. const odd = Object.fromEntries([...m].filter(([, v]) => v % 2 === 1)); produces { x: 1, z: 3 }. Using { ...m } would give {} because object spread copies properties, not Map entries.
Exercise
What does this code log, and why? function* g() { yield 1; yield 2; yield 3; } const it = g(); const [a] = it; console.log(a, [...it]);
Show answer
It logs 1 []. The pattern [a] takes one value and then calls return() on the iterator because it is not finished. That closes the generator, so the later spread gets nothing. Generator objects return themselves from Symbol.iterator, so both operations share one iterator.
Exercise
Why does [...{ 0: 'a', length: 1 }] throw while Array.from({ 0: 'a', length: 1 }) returns ['a']?
Show answer
Spread requires a Symbol.iterator method, and this plain object has none, so spread throws a TypeError. Array.from first looks for an iterator and then falls back to treating the value as array-like, reading length and the numeric indexes.