Sub topic 4
Built-in Iterables You Already Use
This chapter assumes you know arrays, Map, Set, and spread syntax. It also assumes you have read the previous two chapters, which explain that an iterable has a Symbol.iterator method and that this method returns an iterator with next(). Here we look at the iterables the language gives you for free: what each one yields, which of its methods return iterators, and the edge cases that catch people out.
The Built-in Iterables at a Glance
All of these types have a Symbol.iterator method on their prototype. They differ in what each step yields.
| Type | Default iteration yields | Other iterator methods |
|---|---|---|
| `Array` | Element values, in index order | `keys()`, `values()`, `entries()` |
| `String` | Unicode code points, as strings | none |
| `Map` | `[key, value]` pairs, in insertion order | `keys()`, `values()`, `entries()` |
| `Set` | Values, in insertion order | `keys()`, `values()`, `entries()` |
| TypedArray (`Uint8Array` etc.) | Numeric elements | `keys()`, `values()`, `entries()` |
| `arguments` | Argument values | none |
Runtimes add more iterables. Browsers have NodeList, FormData, and URLSearchParams. Node.js has Buffer, which is a Uint8Array, so it iterates as bytes.
The Default Iterator Is Just One of the Methods
For collections, Symbol.iterator is not a separate function. It is the same function object as one of the named methods:
console.log(Array.prototype[Symbol.iterator] === Array.prototype.values); // true
console.log(Map.prototype[Symbol.iterator] === Map.prototype.entries); // true
console.log(Set.prototype[Symbol.iterator] === Set.prototype.values); // true
console.log(Set.prototype.keys === Set.prototype.values); // trueThis tells you what a plain for...of produces. Looping over a Map gives entries, and looping over an array or Set gives values. When you want something else, call the named method:
const colors = ['red', 'green'];
for (const [i, c] of colors.entries()) {
console.log(i, c); // 0 red, then 1 green
}
const ages = new Map([['ann', 31], ['bo', 27]]);
console.log([...ages.keys()]); // [ 'ann', 'bo' ]
console.log([...ages.values()]); // [ 31, 27 ]
const tags = new Set(['js', 'web']);
console.log([...tags.entries()]); // [ [ 'js', 'js' ], [ 'web', 'web' ] ]Set.prototype.entries() yields [value, value]. That looks odd, but it lets code written for Map entries also accept a Set.
The iterators these methods return are iterable themselves. Their Symbol.iterator returns this, which is why for...of accepts colors.entries() directly. Unlike the array, the iterator is a single pass:
const it = [1, 2].values();
console.log(it[Symbol.iterator]() === it); // true
console.log([...it]); // [ 1, 2 ]
console.log([...it]); // [] (already exhausted)Arrays: Holes Become undefined
The array iterator walks every index from 0 to length - 1 and reads each one. Holes in a sparse array therefore show up as undefined. The older callback methods skip holes, so the two styles can disagree:
const sparse = [1, , 3];
console.log([...sparse]); // [ 1, undefined, 3 ]
sparse.forEach(x => console.log('forEach', x)); // forEach 1, forEach 3
for (const x of sparse) console.log('for...of', x); // 1, undefined, 3The array iterator also checks length again on every step. If you push onto an array while iterating over it, the loop sees the new elements, and a loop that pushes on every pass never ends. Iterate over a copy ([...arr]) if the loop body changes the array.
Strings: Code Points, Not Code Units
str.length and str[i] work in UTF-16 code units. The string iterator works in code points, so a character outside the Basic Multilingual Plane, such as most emoji, comes out as one string instead of two broken halves:
const s = 'a😀';
console.log(s.length); // 3
console.log(s[1]); // '\ud83d' (half of a surrogate pair)
console.log([...s]); // [ 'a', '😀' ]
console.log([...s].length); // 2Spreading a string is therefore the simplest correct way to count or reverse code points. It still is not a full "character" split. A flag emoji or a family emoji is several code points joined together, and [...'👍🏽'] gives two items. For what users see as characters (grapheme clusters), use Intl.Segmenter:
const seg = new Intl.Segmenter('en', { granularity: 'grapheme' });
console.log([...seg.segment('👍🏽!')].map(x => x.segment)); // [ '👍🏽', '!' ]That example also shows that segment() returns an iterable. Many newer APIs return iterables rather than arrays.
Map and Set: Insertion Order and Live Iteration
Map and Set iterate in insertion order, which the spec guarantees. Both iterators are live. They see entries added during the loop and skip entries deleted before the loop reaches them:
const s = new Set([1, 2, 3]);
for (const x of s) {
if (x === 1) {
s.delete(2);
s.add(4);
}
console.log(x); // 1, 3, 4
}Deleting the current entry during iteration is safe, which is a common way to prune a Map. Adding entries on every pass has the same danger as pushing onto an array: the loop never finishes.
TypedArrays and arguments
TypedArrays have the same three methods as arrays, and they yield numbers:
const bytes = new Uint8Array([10, 20, 300]);
console.log([...bytes]); // [ 10, 20, 44 ] (300 wraps to 44)
console.log([...bytes.entries()]); // [ [ 0, 10 ], [ 1, 20 ], [ 2, 44 ] ]The arguments object is array-like and also iterable, so you can convert it with spread. In new code, use rest parameters instead:
function legacy() {
return [...arguments];
}
const modern = (...args) => args;
console.log(legacy(1, 2), modern(1, 2)); // [ 1, 2 ] [ 1, 2 ]Arrow functions have no arguments of their own, which is one more reason to prefer rest parameters.
What Is Not Iterable
Plain objects are not iterable. for...of on one throws TypeError: obj is not iterable. That is deliberate: it is unclear whether an object should yield keys, values, or pairs. Choose one explicitly with Object.keys, Object.values, or Object.entries. Each returns an array, and arrays are iterable:
const config = { host: 'localhost', port: 8080 };
for (const [key, value] of Object.entries(config)) {
console.log(key, value); // host localhost, then port 8080
}
const asMap = new Map(Object.entries(config));
console.log(asMap.get('port')); // 8080Array-likes are also not iterable. An array-like is an object with length and numeric keys, such as { 0: 'a', length: 1 }. Spread fails on one, but Array.from works because it falls back to reading length when Symbol.iterator is missing.
To check whether a value is iterable, test for the method. Strings are primitives, but they still pass this check:
const isIterable = v => v != null && typeof v[Symbol.iterator] === 'function';
console.log(isIterable([1])); // true
console.log(isIterable('hi')); // true
console.log(isIterable({ a: 1 })); // false
console.log(isIterable(new Map())); // true
console.log(isIterable(42)); // falseExercise
What does [...new Map([['a', 1]]).keys(), ...'hi', ...new Set([1, 1, 2])] evaluate to, and why?
Show answer
[ 'a', 'h', 'i', 1, 2 ]. keys() yields only the key 'a'. The string yields its code points 'h' and 'i'. The Set holds 1 and 2 once each, because duplicates are dropped when it is built.
Exercise
const word = 'café👋'. Why do word.length and [...word].length differ, and what are their values?
Show answer
word.length counts UTF-16 code units and is 6, because the emoji takes two code units (a surrogate pair). The spread uses the string iterator, which yields code points, so [...word].length is 5. This assumes 'é' is the single precomposed code point U+00E9.
Exercise
A loop runs for (const k of map.keys()) { if (k.startsWith('tmp')) map.delete(k); }. Is this safe, and does it visit every key that existed before the loop?
Show answer
Yes. Map iterators are live, and deleting the current entry does not disturb the iteration, so every remaining key is still visited exactly once. It would only cause problems if the loop added new keys on every pass.