Sub topic 4
Built-in Iterables You Already Use
This chapter assumes you know what the iterable protocol is, meaning an object has a Symbol.iterator method, and that calling next() on an iterator returns { value, done }. It also assumes you have basic experience with arrays, Map, and Set. The chapter covers which built-in values follow these protocols and what each one produces when you iterate it.
Which values are iterable
A value is iterable when it has a callable Symbol.iterator method. You can check that directly:
const isIterable = value =>
value != null && typeof value[Symbol.iterator] === 'function';
console.log(isIterable([1, 2])); // true
console.log(isIterable('hi')); // true
console.log(isIterable(new Map())); // true
console.log(isIterable(new Set())); // true
console.log(isIterable(new Uint8Array(2))); // true
console.log(isIterable({ a: 1 })); // false
console.log(isIterable(42)); // falseEach built-in iterable decides what its default iteration produces:
| Built-in | Default iteration yields | Other iterator methods |
|---|---|---|
| Array | Each element, by index | `keys()`, `values()`, `entries()` |
| String | Each Unicode code point | none |
| Map | `[key, value]` pairs, in insertion order | `keys()`, `values()`, `entries()` |
| Set | Each value, in insertion order | `keys()`, `values()`, `entries()` |
| TypedArray | Each numeric element | `keys()`, `values()`, `entries()` |
| `arguments` | Each argument passed | none |
Strings iterate by code point
String iteration does not go one UTF-16 code unit at a time, which is what length and indexing count. It produces whole code points, so an emoji stays in one piece:
const word = 'a😀';
console.log(word.length); // 3
console.log([...word].length); // 2
for (const ch of word) console.log(ch); // a, then 😀Map and Set have several iterators
Iterating a Map gives you entries. The keys(), values(), and entries() methods return iterators, and those iterators are also iterable, so you can spread them directly:
const scores = new Map([['ann', 3], ['bo', 5]]);
for (const entry of scores) console.log(entry); // [ 'ann', 3 ], then [ 'bo', 5 ]
console.log([...scores.keys()]); // [ 'ann', 'bo' ]
console.log([...scores.values()]); // [ 3, 5 ]
const tags = new Set(['js', 'web']);
console.log([...tags.entries()]); // [ [ 'js', 'js' ], [ 'web', 'web' ] ]Set.prototype.entries() repeats each value as [value, value]. It does this so that Set has the same shape of API as Map.
The arguments object
Inside a regular (non-arrow) function, arguments is an array-like object. It is also iterable:
function sum() {
let total = 0;
for (const n of arguments) total += n;
return total;
}
console.log(sum(1, 2, 3)); // 6In new code, rest parameters (...nums) are clearer and give you a real array.
Plain objects are not iterable
The most common error here is using for...of on an object literal, which throws a TypeError. To loop over a plain object, convert it with Object.keys, Object.values, or Object.entries first:
const user = { name: 'Ann', age: 30 };
try {
for (const x of user) console.log(x);
} catch (e) {
console.log(e instanceof TypeError); // true ("user is not iterable")
}
for (const [key, value] of Object.entries(user)) {
console.log(key, value); // name Ann, then age 30
}Exercise
What does console.log([...new Map([['a', 1]]).values(), ...'hé😀']) print, and why does the string add three elements instead of four?
Show answer
It prints [ 1, 'h', 'é', '😀' ]. The values() iterator yields 1. String iteration yields code points, so the emoji, which is two UTF-16 code units, comes out as one element. (This assumes é is the single precomposed character.)
Exercise
You have const config = { port: 80, host: 'x' }. Write a for...of loop that logs each key and value.
Show answer
for (const [k, v] of Object.entries(config)) console.log(k, v); A plain object has no Symbol.iterator, so Object.entries turns it into an iterable array of [key, value] pairs.