Sub topic 10
Iterating Values with for...of
This chapter assumes you know the classic for loop, break and continue, and array destructuring such as const [a, b] = pair. A for...of loop walks through the values of an iterable: arrays, strings, Maps, Sets, and other collections. It does not use an index counter, and you never write a bounds check.
The basic shape
const scores = [72, 88, 95];
for (const score of scores) {
console.log(score);
}
// 72
// 88
// 95On each pass, the next value is placed in a fresh score binding. Because each iteration gets its own binding, const works here. Use let only if you need to reassign the variable inside the body. Inside a for...of loop, break and continue work the same way they do in a classic for loop.
What counts as an iterable
An iterable is any object with a Symbol.iterator method. That method returns an iterator, which is an object whose next() method hands back { value, done } pairs. The loop calls next() until done is true.
Many built-in types already implement this protocol:
| Iterable | Each value is |
|---|---|
| Array | an element |
| String | one Unicode character (code point) |
| Map | a `[key, value]` pair |
| Set | a member |
| `arguments`, DOM `NodeList` | an element |
Strings, Maps, and Sets
A for...of loop over a string yields whole characters, even ones made of two UTF-16 code units, such as many emoji. Indexing with str[i] would split those characters in half.
const word = "a😀";
console.log(word.length); // 3
for (const ch of word) {
console.log(ch);
}
// "a"
// "😀"Map entries arrive as pairs, so destructure them in the loop header:
const stock = new Map([["apples", 4], ["pears", 0]]);
for (const [fruit, count] of stock) {
console.log(`${fruit}: ${count}`);
}
// apples: 4
// pears: 0
const tags = new Set(["js", "web", "js"]);
for (const tag of tags) {
console.log(tag); // "js", "web"
}Getting the index too
If you need the position as well as the value, iterate array.entries(). It yields [index, value] pairs:
const colors = ["red", "green"];
for (const [i, color] of colors.entries()) {
console.log(i, color);
}
// 0 "red"
// 1 "green"Common errors
Plain objects are not iterable. for (const x of { a: 1 }) throws TypeError: {} is not iterable. To loop over an object, pick the view you want with Object.keys(obj), Object.values(obj), or Object.entries(obj). Each of these returns an array.
const prices = { tea: 3, coffee: 4 };
for (const [item, price] of Object.entries(prices)) {
console.log(item, price);
}
// tea 3
// coffee 4Exercise
What does this code print, and why? for (const c of new Set("hello")) console.log(c);
Show answer
It prints h, e, l, o on separate lines. The Set constructor iterates the string character by character and stores each unique value once, so the second "l" is dropped. The for...of loop then yields the Set's members in insertion order.
Exercise
A teammate writes for (const key of user) { ... } where user is a plain object, and gets a TypeError. Give two ways to fix it, depending on whether they need keys only or keys and values.
Show answer
Plain objects don't implement Symbol.iterator. For keys only, use for (const key of Object.keys(user)). For both, use for (const [key, value] of Object.entries(user)).