Sub topic 9
Destructuring Entries Inside for...of
This chapter assumes you already know for...of syntax, the built-in iterables (Array, String, Map, Set), and basic destructuring assignment with const [a, b] = pair and const { x } = obj. It shows how to put a destructuring pattern directly in the loop head, so each value the iterable produces is unpacked into named variables before the loop body runs.
Why Destructure in the Loop Head
Many iterables produce pairs instead of single values. A Map yields [key, value] arrays. Array.prototype.entries() yields [index, element] arrays. Without destructuring, you index into each pair by hand:
const prices = new Map([['apple', 1.2], ['pear', 0.8]]);
for (const entry of prices) {
console.log(`${entry[0]}: ${entry[1]}`);
}
// apple: 1.2
// pear: 0.8entry[0] and entry[1] say nothing about what they hold. A pattern in the loop head gives each part a name:
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'The loop declares one binding per name in the pattern. With const, each iteration gets fresh fruit and price bindings that you cannot reassign inside the body.
What Happens on Each Iteration
for...of asks the iterator for its next value. When it gets one, it runs the destructuring pattern against that value, exactly as const [fruit, price] = value would, and then executes the body.
So any rule you know from ordinary destructuring also applies in the loop head: defaults, skipping, renaming, nesting, and rest elements.
Which Iterables Produce Pairs
| Source | Each value | Typical pattern |
|---|---|---|
| `map` or `map.entries()` | `[key, value]` | `[key, value]` |
| `map.keys()` / `map.values()` | single key or value | plain name |
| `array.entries()` | `[index, element]` | `[i, item]` |
| `set` or `set.values()` | single value | plain name |
| `set.entries()` | `[value, value]` | `[value]` |
| `Object.entries(obj)` | `[key, value]` | `[key, value]` |
Set.prototype.entries() repeats the value twice so that its shape matches Map. You seldom need it, but it explains this output:
const tags = new Set(['js', 'loops']);
for (const [a, b] of tags.entries()) {
console.log(a, b);
}
// js js
// loops loopsObject.entries gets its own chapter next. Here, all you need to know is that it produces the same [key, value] shape, so the same pattern works on it.
Pattern Features That Work in the Loop Head
Skipping Parts
Leave a slot empty to ignore part of a pair. This is handy when you only need the values of entries() but still want the index for some other purpose, or the other way round:
const stock = new Map([['apple', 4], ['pear', 0], ['plum', 7]]);
for (const [, count] of stock) {
console.log(count);
}
// 4
// 0
// 7If you only ever need one side of a Map, stock.values() or stock.keys() says that more clearly than a skipped slot.
Defaults
A default applies when the destructured slot is undefined. Sparse arrays are one place where this matters, because entries() reports holes as undefined:
const slots = ['a', , 'c'];
for (const [i, value = '(empty)'] of slots.entries()) {
console.log(i, value);
}
// 0 a
// 1 (empty)
// 2 cA default does not apply to null. Only undefined triggers it.
Object Patterns Over Arrays of Records
The value doesn't have to be a pair. When you iterate an array of objects, an object pattern pulls out the fields you need and can rename them or give them defaults:
const users = [
{ name: 'Ada', role: 'admin' },
{ name: 'Alan' },
];
for (const { name: userName, role = 'guest' } of users) {
console.log(userName, role);
}
// Ada admin
// Alan guestNesting
Patterns nest as deep as the data does. Here a Map's values are objects that contain arrays:
const projects = new Map([
[101, { title: 'Parser', tags: ['core', 'fast'] }],
[102, { title: 'CLI', tags: ['tooling'] }],
]);
for (const [id, { title, tags: [firstTag, ...otherTags] }] of projects) {
console.log(id, title, firstTag, otherTags);
}
// 101 Parser core [ 'fast' ]
// 102 CLI tooling []Use nesting with restraint. Once a pattern stops fitting on one readable line, destructure the outer pair in the loop head and unpack the rest in the body.
Common Errors
Using an Object Pattern on Map Entries
A Map entry is an array, not an object with key and value properties. This pattern runs without an error but gives you nothing useful:
const prices = new Map([['apple', 1.2]]);
for (const { key, value } of prices) {
console.log(key, value);
}
// undefined undefinedUse [key, value] for entries.
Destructuring a Value That Isn't Iterable or Is null
An array pattern needs an iterable value. An object pattern needs a value other than null or undefined. If one bad element appears in the data, the loop throws a TypeError partway through:
const rows = [[1, 2], null, [3, 4]];
try {
for (const [a, b] of rows) {
console.log(a, b);
}
} catch (err) {
console.log(err instanceof TypeError); // true
}
// 1 2
// trueThe first row is logged before the error. If the data can contain gaps, destructure in the body after you check the value, or filter the data first:
const rows = [[1, 2], null, [3, 4]];
for (const row of rows) {
if (!Array.isArray(row)) continue;
const [a, b] = row;
console.log(a, b);
}
// 1 2
// 3 4Expecting Writes to Bindings to Update the Collection
The bindings are copies of what the pattern extracted. Reassigning them (with let) changes only the local variable. The Map and the array stay the same:
const prices = new Map([['apple', 1.2]]);
for (let [fruit, price] of prices) {
price = price * 2;
}
console.log(prices.get('apple')); // 1.2
for (const [fruit, price] of prices) {
prices.set(fruit, price * 2);
}
console.log(prices.get('apple')); // 2.4To change the collection, call its own methods, such as map.set(key, newValue) or array[i] = newValue, using the destructured key or index. Overwriting an existing Map key during iteration is safe. Adding and deleting entries while you loop is covered in a later chapter.
Forgetting entries() on Arrays
for (const [i, item] of array) destructures each element, not an index-element pair. If the elements are strings, you get their first two characters:
const names = ['Ada', 'Alan'];
for (const [i, item] of names) {
console.log(i, item);
}
// A d
// A l
for (const [i, item] of names.entries()) {
console.log(i, item);
}
// 0 Ada
// 1 AlanExercises
Exercise
What does this code log, and why? const m = new Map([['a', 1], ['b', 2]]); for (const [k, v = 0] of m) console.log(k, v); for (const { 0: k, 1: v } of m) console.log(k, v);
Show answer
Both loops log "a 1" and then "b 2". In the first loop, the default 0 is never used because no value is undefined. The second loop works because each entry is an array, and an object pattern can read the array's properties "0" and "1" by name. It is valid JavaScript, but [k, v] is clearer.
Exercise
You have const scores = ['90', , '75']. Write a for...of loop that logs each index with the score as a number, using 0 for the hole.
Show answer
for (const [i, s = '0'] of scores.entries()) { console.log(i, Number(s)); } logs 0 90, 1 0, 2 75. entries() reports the hole as undefined, which triggers the default.
Exercise
A loop of the form for (const { id, meta: { owner } } of records) throws "TypeError: Cannot read properties of undefined" on the third record. What is the probable cause, and what are two ways to fix it?
Show answer
The third record has no meta property, so the nested pattern tries to destructure undefined. One fix is a default on the nested pattern: for (const { id, meta: { owner } = {} } of records). This makes owner undefined for that record. The other fix is to destructure only { id, meta } in the loop head, then check meta inside the body before you read owner.