Sub topic 2
What You Can Loop Over: Arrays, Strings, Maps, Sets and More
This chapter assumes you know let and const, array and object basics, and the for...in and for...of syntax covered earlier.
Built-in Iterables
for...of works on any iterable. An iterable is a value that knows how to produce its items one at a time. Arrays, strings, Maps, Sets, arguments and DOM NodeLists are all built-in iterables. Plain objects are not.
| Source | What `for...of` yields |
|---|---|
| Array | Element values |
| String | Characters, one code point each |
| Map | `[key, value]` pairs |
| Set | Unique values in insertion order |
for (const n of new Set([1, 2, 2, 3])) {
console.log(n);
}
// 1
// 2
// 3Strings, Emoji and Code Points
A string's length counts UTF-16 code units. for...of counts code points instead, so an emoji stored as two code units comes out as one value.
for (const ch of 'a😀') {
console.log(ch);
}
// a
// 😀
console.log('a😀'.length); // 3Indexing with str[i] would split the emoji into two broken halves.
Destructuring Entries
Maps and Array.prototype.entries() produce [key, value] pairs. You can unpack each pair in the loop head.
const prices = new Map([['apple', 1.2], ['pear', 0.8]]);
for (const [fruit, price] of prices) {
console.log(`${fruit}: ${price}`);
}
const letters = ['x', 'y'];
for (const [index, letter] of letters.entries()) {
console.log(index, letter);
}
// 0 'x'
// 1 'y'Looping Over Plain Objects
for (const v of {}) throws a TypeError. To loop over a plain object, convert it first. Object.keys, Object.values and Object.entries return arrays built from the object's own enumerable string-keyed properties, and inherited properties are skipped.
const scores = { ada: 9, alan: 7 };
for (const [name, score] of Object.entries(scores)) {
console.log(name, score);
}
// ada 9
// alan 7Why Not for...in on Arrays
for...in gives you keys as strings. On an array, it also includes any extra enumerable properties, plus enumerable properties inherited from the prototype.
const arr = [10, 20, 30];
arr.extra = 'x';
for (const i in arr) {
console.log(typeof i, i);
}
// string 0
// string 1
// string 2
// string extra
for (const value of arr) {
console.log(value);
}
// 10
// 20
// 30A common bug is i + 1 returning '01', because i is a string. Use for...of, or entries() when you need the index too.
Exercise
You need each index and value of an array items, with the index as a number. Write the loop.
Show answer
for (const [i, item] of items.entries()) { console.log(i, item); } — entries() yields [number, value] pairs, unlike for...in, which yields string keys.
Exercise
What does for (const c of 'hi👋') count++ leave in count (starting at 0), and what is 'hi👋'.length?
Show answer
count is 3, because the emoji is one code point. The length is 4, because the emoji takes two UTF-16 code units.