Sub topic 12
Adding and Deleting Properties While Looping
This chapter assumes you know how Object.keys and Object.entries return arrays, how to destructure [key, value] pairs in a for...of loop, and how for...in differs from Object.keys. The question here is narrow: what happens when the loop body changes the object you are looping over?
The Key Array Is a Snapshot
Object.keys(obj) reads the object once and returns a new, ordinary array. The for...of loop then walks that array, not the object. Changes you make to the object later do not alter the array, so they do not alter which keys the loop visits.
This makes the common cleanup task safe. Deleting the key you are currently visiting has no effect on the rest of the loop:
const settings = { theme: 'dark', font: null, size: 14, color: undefined };
for (const key of Object.keys(settings)) {
if (settings[key] == null) {
delete settings[key];
}
}
console.log(settings); // { theme: 'dark', size: 14 }Deleting a Key You Have Not Reached Yet
The snapshot has a side effect. If you delete a key that comes later in the array, the loop still visits it, because the array still holds that string. Reading the property now gives undefined:
const stock = { apples: 3, pears: 0, plums: 5 };
for (const key of Object.keys(stock)) {
if (key === 'apples') delete stock.plums;
console.log(key, stock[key]);
}
// apples 3
// pears 0
// plums undefinedIf the loop body can remove other keys, check that the key still exists before you use it. Object.hasOwn (ES2022) is the direct test:
const stock = { apples: 3, pears: 0, plums: 5 };
for (const key of Object.keys(stock)) {
if (!Object.hasOwn(stock, key)) continue;
if (key === 'apples') delete stock.plums;
console.log(key, stock[key]);
}
// apples 3
// pears 0Adding Keys During the Loop
New properties are not in the snapshot, so the loop never visits them. This also means a loop that adds keys cannot run forever:
const counts = { a: 1, b: 2 };
for (const key of Object.keys(counts)) {
counts[key + '_double'] = counts[key] * 2;
}
console.log(counts); // { a: 1, b: 2, a_double: 2, b_double: 4 }The body ran twice, once for a and once for b.
Values in Object.entries Are Snapshots Too
Object.entries copies each value along with its key when it is called. If you change a property during the loop, the destructured value for a later entry still holds the old value:
const totals = { x: 1, y: 2 };
for (const [key, value] of Object.entries(totals)) {
totals.y = 100;
console.log(key, value);
}
// x 1
// y 2
console.log(totals.y); // 100If you need the current value, read totals[key] instead of relying on value.
How for...in Behaves Instead
for...in walks the object live instead of using a snapshot. The specification guarantees that a property deleted before the loop reaches it is skipped. It does not guarantee whether properties added during the loop will be visited.
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (key === 'a') delete obj.c;
console.log(key);
}
// a
// b| Change during loop | `for...of` over `Object.keys` | `for...in` |
|---|---|---|
| Delete current key | Safe | Safe |
| Delete a later key | Still visited, value `undefined` | Skipped |
| Add a new key | Never visited | Not guaranteed either way |
| Change a later value | `Object.entries` gives the old value | Reads the current value |
Prefer Building a New Object
Mutating an object while looping over it works, but the loop body then has to reason about which changes the loop can see. You can often avoid that by leaving the original untouched and building a result with Object.fromEntries:
const settings = { theme: 'dark', font: null, size: 14, color: undefined };
const cleaned = Object.fromEntries(
Object.entries(settings).filter(([, value]) => value != null)
);
console.log(cleaned); // { theme: 'dark', size: 14 }
console.log(settings); // original is unchangedMutate in place only when other code holds a reference to the same object and needs to see the change.
Exercise
Given const o = { a: 1, b: 2, c: 3 };, what does this print: for (const k of Object.keys(o)) { if (k === 'a') { delete o.b; o.d = 4; } console.log(k, o[k]); }?
Show answer
It prints a 1, b undefined, c 3. The key array ['a', 'b', 'c'] was fixed before the loop started. b is still visited even though it was deleted, so its value reads as undefined. The added key d is never visited.
Exercise
You loop with for (const [k, v] of Object.entries(prices)) and double every price by assigning prices[k] = v * 2. Halfway through, the body also sets prices.last = 0 for a key that comes later. What value does v hold when the loop reaches last, and what ends up in prices.last?
Show answer
v holds the original value of last, because Object.entries copied the values before the loop began. The loop then assigns prices.last = original * 2, which overwrites the 0. To double the current value, use prices[k] * 2 instead of v * 2.