Sub topic 5
Destructuring [key, value] in for...of
This chapter assumes you know how to declare variables with const and let, write object literals, and use for...of over arrays. It also assumes you have read the previous chapter, where Object.entries turned an object into an array of [key, value] pairs. Here you learn to unpack those pairs directly in the loop head, and you see the mistakes people make most often when doing it.
From pair to named variables
Each item Object.entries produces is a two-element array. You could index into it by hand:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const pair of Object.entries(scores)) {
console.log(pair[0], pair[1]);
}That works, but pair[0] and pair[1] say nothing about what they hold. Array destructuring is syntax that assigns array elements to variables by position. You can put the destructuring pattern straight 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: 85On each pass, for...of takes the next pair and the pattern [name, score] binds position 0 to name and position 1 to score. The names are your choice. Pick ones that describe the data rather than the generic key and value.
Going further with the pattern
Destructuring patterns nest. When the values are themselves objects, you can unpack them in the same line:
const users = {
ada: { age: 36, role: 'admin' },
bob: { age: 25, role: 'user' }
};
for (const [name, { age, role }] of Object.entries(users)) {
console.log(`${name} (${age}) is ${role}`);
}
// ada (36) is admin
// bob (25) is userYou can also give a default. A default applies only when the value is undefined. It does not apply to null:
const stock = { apples: 4, pears: undefined, plums: null };
for (const [fruit, count = 0] of Object.entries(stock)) {
console.log(fruit, count);
}
// apples 4
// pears 0
// plums nullCommon errors
| Mistake | What happens | Fix |
|---|---|---|
| `for (const [k, v] of scores)` | `TypeError: scores is not iterable` | Loop over `Object.entries(scores)` |
| `for (const { key, value } of Object.entries(scores))` | Both variables are `undefined` | Use square brackets, because each pair is an array |
| Reassigning `score` inside the loop | The object does not change | Write back with `scores[name] = ...` |
The first mistake is the most common. Plain objects are not iterable, so for...of refuses them:
const scores = { alice: 90, bob: 72 };
try {
for (const [name, score] of scores) {
console.log(name, score);
}
} catch (err) {
console.log(err instanceof TypeError); // true
}The third mistake comes from expecting the loop variable to be linked to the object. Destructuring copies values into new variables:
const scores = { alice: 90, bob: 72 };
for (let [name, score] of Object.entries(scores)) {
score += 10; // changes only the local variable
}
console.log(scores); // { alice: 90, bob: 72 }
for (const [name, score] of Object.entries(scores)) {
scores[name] = score + 10; // updates the object
}
console.log(scores); // { alice: 100, bob: 82 }Exercise
Given const inventory = { hammer: { qty: 3 }, saw: { qty: 0 }, drill: { qty: 5 } };, write a for...of loop that uses nested destructuring to log only the tool names whose qty is greater than 0.
Show answer
for (const [tool, { qty }] of Object.entries(inventory)) { if (qty > 0) console.log(tool); } logs "hammer" and then "drill". The outer brackets unpack the [key, value] pair, and the inner braces pull qty out of each value object.
Exercise
A teammate writes for (const { name, score } of Object.entries(scores)) console.log(name, score); and sees "undefined undefined" on every line. Explain why and fix it.
Show answer
Each entry is an array like ['alice', 90], not an object with name and score properties, so object destructuring finds nothing and both variables come out undefined. Use array destructuring instead: for (const [name, score] of Object.entries(scores)) console.log(name, score);