Sub topic 7
What You Can Loop Over: Arrays, Strings, Maps, Sets and More
This chapter assumes you know the basic for...of syntax from the previous chapter, plus arrays, objects and functions. Here we look at which built-in values for...of accepts and what each one yields.
The rule: it must be iterable
for...of works on any iterable, meaning a value that knows how to produce its own sequence of values. Many built-in types are iterable out of the box. Plain objects are not, and a later chapter covers how to loop over them.
| Value | What each iteration yields |
|---|---|
| Array | Each element, in index order |
| String | Each character (by code point) |
| Map | A `[key, value]` pair, in insertion order |
| Set | Each value, in insertion order |
| `arguments` | Each argument passed to the function |
| NodeList (browser) | Each DOM node |
| Typed arrays such as `Uint8Array` | Each number |
Arrays and strings
for (const n of [3, 1, 4]) {
console.log(n);
}
// 3
// 1
// 4
for (const ch of 'hey') {
console.log(ch);
}
// h
// e
// yStrings yield one character at a time. Emoji and other characters outside the basic range have extra rules, which the next chapter covers.
Maps and Sets
A Map yields two-element arrays. A Set yields its values. Both keep insertion order, and a Set never repeats a value.
const roles = new Map([['ada', 'admin'], ['alan', 'editor']]);
for (const entry of roles) {
console.log(entry);
}
// ['ada', 'admin']
// ['alan', 'editor']
const tags = new Set(['js', 'loops', 'js']);
for (const tag of tags) {
console.log(tag);
}
// js
// loopsMaps also give you keys(), values() and entries(), which return iterables you can loop over directly:
const roles = new Map([['ada', 'admin'], ['alan', 'editor']]);
for (const name of roles.keys()) {
console.log(name);
}
// ada
// alanArrays and Sets have the same three methods.
arguments and NodeList
The arguments object inside a regular (non-arrow) function is iterable:
function total() {
let sum = 0;
for (const n of arguments) {
sum += n;
}
return sum;
}
console.log(total(1, 2, 3)); // 6In browsers, document.querySelectorAll returns a NodeList, which is also iterable:
// Run in a browser console
for (const link of document.querySelectorAll('a')) {
console.log(link.href);
}Exercises
Exercise
What does this log? for (const x of new Set([2, 2, 5])) console.log(x);
Show answer
It logs 2 and then 5. A Set stores each value once and yields values in insertion order.
Exercise
Given const m = new Map([['a', 1]]);, what is the value of item in for (const item of m)?
Show answer
item is the array ['a', 1]. Iterating a Map yields [key, value] pairs.
Exercise
Why does for (const v of { a: 1 }) throw, while for (const v of [1]) works?
Show answer
Arrays are built-in iterables and plain objects are not. for...of needs an iterable, so it throws a TypeError on the plain object.