Sub topic 9
Destructuring Entries Inside for...of
This chapter assumes you already know for...of syntax, the built-in iterables (arrays, strings, Maps, Sets), and array destructuring such as const [a, b] = pair.
Many iterables produce pairs instead of single values. A Map produces [key, value] arrays, and Array.prototype.entries() produces [index, element] arrays. You could read each pair with pair[0] and pair[1], but destructuring in the loop head names both parts at once.
The Pattern
The loop variable declaration can be any destructuring pattern. On each iteration, JavaScript takes the next value and unpacks it into the names you wrote.
const prices = new Map([['apple', 1.2], ['pear', 0.8]]);
for (const [fruit, price] of prices) {
console.log(`${fruit}: ${price}`);
}
// apple: 1.2
// pear: 0.8
const letters = ['x', 'y'];
for (const [index, letter] of letters.entries()) {
console.log(index, letter);
}
// 0 x
// 1 yA Map's default iterator is entries(), so for (const [k, v] of map) and for (const [k, v] of map.entries()) behave the same. To get only keys or only values, use map.keys() or map.values() and skip destructuring.
Which Iterables Yield Pairs
| Source | Each value | Typical pattern |
|---|---|---|
| `map` or `map.entries()` | `[key, value]` | `[key, value]` |
| `array.entries()` | `[index, element]` | `[i, item]` |
| `set.entries()` | `[value, value]` | rarely useful |
| An array of tuples | whatever you stored | `[x, y]` |
Going Further: Nesting, Skipping, Defaults
The full destructuring syntax works in the loop head, so you can nest object patterns, skip positions, and supply defaults.
const users = new Map([
['ada', { role: 'admin', age: 36 }],
['alan', { role: 'editor' }],
]);
for (const [name, { role, age = 'unknown' }] of users) {
console.log(name, role, age);
}
// ada admin 36
// alan editor unknown
const points = [[1, 2, 3], [4, 5, 6]];
for (const [, y] of points) {
console.log(y);
}
// 2
// 5Common Errors
- Destructuring a non-pair. In
for (const [a, b] of ['hi', 'yo']), each string gets destructured by character, soais'h'andbis'i'. JavaScript throws no error here, so the bug is easy to miss. - Forgetting
.entries()on arrays.for (const [i, v] of arr)tries to destructure each element, not an index-and-value pair. If the elements are numbers, it throwsTypeErrorbecause numbers are not iterable. - Object pattern on a Map entry.
for (const { key, value } of map)givesundefinedfor both, because entries are arrays, not objects.
Exercise
Given const stock = new Map([['pen', { qty: 3 }], ['ink', {}]]);, write a for...of loop that logs each item name and its qty, using 0 when qty is missing.
Show answer
for (const [item, { qty = 0 }] of stock) { console.log(item, qty); } logs pen 3 and then ink 0. The outer array pattern unpacks the Map entry, and the inner object pattern pulls out qty with a default of 0.
Exercise
What does for (const [i, v] of ['a', 'b']) console.log(i, v); print, and how do you fix it to print indices?
Show answer
It prints a undefined and then b undefined, because each one-character string is destructured by character. Iterate ['a', 'b'].entries() instead to get 0 a and 1 b.