Sub topic 5
Destructuring [key, value] in for...of
This chapter assumes you know const and let, template literals, arrays and for...of, and what Object.entries returns, which the previous chapter covered: an array of [key, value] pairs. Here the focus is the loop head itself. It covers how the [key, value] pattern unpacks each pair, what you can put inside that pattern, and the mistakes that cause silent bugs.
What the Pattern Replaces
Each element that Object.entries returns is a two-element array. Without destructuring, you index into it yourself:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const pair of Object.entries(scores)) {
const name = pair[0];
const score = pair[1];
console.log(`${name}: ${score}`);
}
// alice: 90
// bob: 72
// carol: 85Array destructuring moves those two assignments into the loop head:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
// alice: 90
// bob: 72
// carol: 85The two loops behave the same way. On each iteration, for...of takes the next element of the array, and the pattern [name, score] binds name to position 0 and score to position 1. The pattern matches by position, so the variable names are up to you. Choose names that describe the data, such as [name, score], [sku, price] or [userId, user], instead of the generic [key, value].
const, let, and Fresh Bindings Each Iteration
Every iteration of for...of creates new bindings. That is why const works in the loop head even though the variables take different values on each pass. The value doesn't change inside one iteration. The next iteration gets a new variable.
Fresh bindings also mean closures capture the values you expect:
const scores = { alice: 90, bob: 72, carol: 85 };
const reporters = [];
for (const [name, score] of Object.entries(scores)) {
reporters.push(() => `${name}=${score}`);
}
console.log(reporters.map((report) => report()));
// ['alice=90', 'bob=72', 'carol=85']Use const by default. Use let only if you need to reassign the variable inside the body, for example to normalize it:
const prices = { apple: '1.20', pear: '0.80' };
for (let [fruit, price] of Object.entries(prices)) {
price = Number(price);
console.log(fruit, price.toFixed(1));
}
// apple 1.2
// pear 0.8Skipping Positions
You can leave a position empty in the pattern. A leading comma skips the key:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const [, score] of Object.entries(scores)) {
console.log(score);
}
// 90
// 72
// 85This works, but if you never need the key, Object.values(scores) says so more clearly. Skipping is more useful in callbacks that receive pairs, which the next chapter covers. If you need only the key, write [name]. The pattern ignores the elements after it.
Nested Destructuring for Object Values
When the values are themselves objects, you can destructure them in the same loop head by putting an object pattern in the second position:
const users = {
u1: { name: 'Ada', role: 'admin' },
u2: { name: 'Lin', role: 'editor' },
};
for (const [id, { name, role }] of Object.entries(users)) {
console.log(`${id}: ${name} (${role})`);
}
// u1: Ada (admin)
// u2: Lin (editor)The outer [ ] matches the pair by position. The inner { } matches the value's properties by name. You can rename properties with property: newName and give defaults with =:
const users = {
u1: { name: 'Ada', role: 'admin' },
u2: { name: 'Lin' },
};
for (const [id, { name: displayName, role = 'viewer' }] of Object.entries(users)) {
console.log(`${id}: ${displayName} (${role})`);
}
// u1: Ada (admin)
// u2: Lin (viewer)Nest the patterns only as deep as stays readable. If a loop head gets longer than the body, destructure inside the body instead.
Defaults Cover undefined, Not null
A default applies only when the value at that position is undefined. Destructuring { name } from null throws, and a default on the whole value does not help, because null is not undefined:
const users = {
u1: { name: 'Ada' },
u2: undefined,
u3: null,
};
for (const [id, { name } = { name: 'unknown' }] of Object.entries(users)) {
console.log(id, name);
}
// u1 Ada
// u2 unknown
// TypeError: Cannot destructure property 'name' of ... as it is null.The exact wording of the error message depends on the engine. If the data can contain null, destructure the pair only, and check the value in the body:
const users = { u1: { name: 'Ada' }, u2: undefined, u3: null };
for (const [id, user] of Object.entries(users)) {
const name = user?.name ?? 'unknown';
console.log(id, name);
}
// u1 Ada
// u2 unknown
// u3 unknownGetting an Index Too
for...of gives you no counter. To number the pairs, call the array's own .entries() method on the result of Object.entries. It yields [index, element], and here each element is itself a pair, so the pattern nests:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const [i, [name, score]] of Object.entries(scores).entries()) {
console.log(`${i + 1}. ${name}: ${score}`);
}
// 1. alice: 90
// 2. bob: 72
// 3. carol: 85The two methods have almost the same name and are easy to mix up. Object.entries(obj) is a static method that returns an array of key-value pairs. array.entries() is an array method that returns an iterator of index-element pairs.
Common Errors
Using an Object Pattern Instead of an Array Pattern
Each pair is an array, not an object with key and value properties. An object pattern runs without an error and gives undefined:
const scores = { alice: 90 };
for (const { key, value } of Object.entries(scores)) {
console.log(key, value);
}
// undefined undefinedUse square brackets: [key, value].
Looping over the Object Directly
Plain objects are not iterable, so for...of rejects them right away:
const scores = { alice: 90 };
try {
for (const [name, score] of scores) {
console.log(name, score);
}
} catch (err) {
console.log(err instanceof TypeError); // true (scores is not iterable)
}Wrap the object in Object.entries(...).
Destructuring Keys Instead of Entries
This bug is quieter. Strings are iterable, so destructuring a key string splits it into characters:
const scores = { alice: 90, bob: 72 };
for (const [name, score] of Object.keys(scores)) {
console.log(name, score);
}
// a l
// b oNo error is thrown, and the output looks almost plausible. If name comes out as a single letter, check whether you called Object.keys where you meant Object.entries.
Expecting Live Values
The pairs are copied when Object.entries runs. If the body changes scores[name], the score variable for that iteration keeps its old value. The last chapter covers changing an object while you loop over it.
The Same Pattern Elsewhere
The [key, value] pattern works with anything that yields two-element arrays, so it carries over to other key-value structures:
| Source | Loop head | Needs a conversion call? |
|---|---|---|
| Plain object | `for (const [k, v] of Object.entries(obj))` | Yes, `Object.entries` |
| `Map` | `for (const [k, v] of map)` | No, a Map yields pairs directly |
| `URLSearchParams` | `for (const [k, v] of params)` | No |
| Array with index | `for (const [i, item] of arr.entries())` | Yes, `.entries()` |
const stock = new Map([['apple', 3], ['pear', 0]]);
for (const [fruit, count] of stock) {
console.log(`${fruit}: ${count}`);
}
// apple: 3
// pear: 0Learn the pattern once and you can use it in all of these places.
Exercise
Given const inventory = { apple: { qty: 3, price: 1.2 }, pear: { qty: 0, price: 0.8 } };, write a for...of loop that destructures each pair into the fruit name plus qty and price, and logs only in-stock fruits as "apple: 3 x 1.2".
Show answer
for (const [fruit, { qty, price }] of Object.entries(inventory)) { if (qty > 0) console.log(${fruit}: ${qty} x ${price}); } It logs only "apple: 3 x 1.2". The outer array pattern matches the [key, value] pair by position, and the inner object pattern pulls qty and price out of the value by name.
Exercise
A teammate writes for (const [k, v] of Object.keys(config)) console.log(k, v); for const config = { mode: 'dev', port: 8080 };. What does it print, and how do you fix it?
Show answer
It prints "m o" and then "p o", because each key is a string, and array destructuring takes its first two characters. Replace Object.keys with Object.entries to get "mode dev" and "port 8080".
Exercise
Inside for (let [name, score] of Object.entries(scores)) you write score += 5. Does scores change? If not, what line makes the bonus stick?
Show answer
No. score is a local binding that holds a copy of the value. Write scores[name] = score + 5 (or scores[name] += 5) to update the object.