Sub topic 12
Adding and Deleting Properties While Looping
This chapter assumes you are comfortable with Object.keys, Object.entries, destructuring in for...of, for...in, and Object.fromEntries, all covered earlier in this tutorial. It answers one practical question: what happens when the loop body changes the object you are looping over?
The short answer is that Object.keys, Object.values, and Object.entries return a snapshot, so most changes are safe. A snapshot still has limits. It can hand you a key that no longer exists, or a value that has since changed. This chapter covers those cases and shows when to build a new object instead.
The Snapshot Model
When you call Object.keys(obj), JavaScript reads the object's own enumerable string keys at that moment and copies them into a new, ordinary array. The for...of loop then walks that array. The array has no link back to the object. Adding or deleting properties later changes the object but not the array.
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 }The loop visits all four keys, theme, font, size, and color, because the array was built before any deletion happened. Deleting font removes it from settings, but the string 'font' is still in the array, and the loop has already moved past it. The check settings[key] == null uses loose equality, so it matches both null and undefined.
Adding Properties During a Snapshot Loop
Because the key list is fixed, properties you add inside the loop are never visited. This lets you safely add derived properties next to existing ones:
const stock = { apples: 3, pears: 0 };
for (const key of Object.keys(stock)) {
stock[`${key}InStock`] = stock[key] > 0;
}
console.log(stock);
// { apples: 3, pears: 0, applesInStock: true, pearsInStock: false }If the loop visited new keys, this code would never finish. It would add applesInStockInStock, and then a longer key after that, without end. The snapshot rules that out.
Renaming Keys in Place
Renaming means adding a new key and deleting the old one. Both happen safely under a snapshot:
const row = { first_name: 'Ada', last_name: 'Lovelace', id: 1 };
for (const key of Object.keys(row)) {
const camel = key.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
if (camel !== key) {
row[camel] = row[key];
delete row[key];
}
}
console.log(row); // { id: 1, firstName: 'Ada', lastName: 'Lovelace' }The new key order deserves a look. id comes first now. Each renamed key is added at the end of the insertion order, and its old position is removed. If later code or a test depends on key order, renaming in place reorders the object.
A second risk is collision. If row already had a firstName property, the assignment would overwrite it without any warning. Check with Object.hasOwn(row, camel) before writing if that could happen.
Common Errors
Visiting a Key You Already Deleted
The snapshot doesn't know about deletions. If the body deletes a key that comes later in the array, the loop still reaches that key, and reading it gives undefined:
const queue = { first: 'x', second: 'y', third: 'z' };
for (const key of Object.keys(queue)) {
if (key === 'first') {
delete queue.third;
}
console.log(key, queue[key]);
}
// first x
// second y
// third undefinedThis bug is easy to miss, because undefined often flows through later code without throwing. If the body can delete keys other than the current one, check that the key still exists before using it:
const queue = { first: 'x', second: 'y', third: 'z' };
for (const key of Object.keys(queue)) {
if (!Object.hasOwn(queue, key)) continue;
if (key === 'first') {
delete queue.third;
}
console.log(key, queue[key]);
}
// first x
// second yObject.hasOwn (ES2022) is the modern replacement for Object.prototype.hasOwnProperty.call(obj, key). Don't test queue[key] !== undefined here. A property can exist and still hold undefined.
Reading Stale Values from Object.entries
Object.entries copies the keys and also the values at the moment of the call. A value destructured from an entry does not change when the object changes:
const counts = { a: 1, b: 2 };
for (const [key, value] of Object.entries(counts)) {
counts.b = 100;
console.log(key, value);
}
// a 1
// b 2
console.log(counts.b); // 100On the second pass, value is still 2 even though counts.b is now 100. When the body changes values that later iterations depend on, read obj[key] rather than the destructured value. The same applies to Object.values, which has no key at all, so you cannot re-read the current value from it.
If the values are objects, the snapshot copies references, not the objects. Changing value.count inside the loop changes the original nested object, because both point to the same thing. Only reassigning the top-level property is invisible to the snapshot.
Relying on for...in Behavior
for...in does not use a public snapshot array. The specification sets two rules for it:
- A property deleted before the loop reaches it is skipped.
- A property added during the loop may or may not be visited. The specification makes no promise either way.
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (key === 'a') {
delete obj.c;
}
console.log(key);
}
// a
// bDeleting ahead of the loop is therefore safe with for...in, and it avoids the undefined problem shown earlier. Adding properties is different. Current engines generally don't visit new properties, but code that depends on that relies on unspecified behavior. When the body adds properties, use Object.keys.
Mutate in Place or Build a New Object?
Often the clearest fix is to leave the original object alone. The cleanup loop at the start of this chapter can be written without mutation:
const settings = { theme: 'dark', font: null, size: 14, color: undefined };
const clean = Object.fromEntries(
Object.entries(settings).filter(([, value]) => value != null)
);
console.log(clean); // { theme: 'dark', size: 14 }
console.log(settings); // { theme: 'dark', font: null, size: 14, color: undefined }The two approaches have different trade-offs:
| Concern | Mutate in place | Build a new object |
|---|---|---|
| Other references to the object | See the change, which may be wanted or a bug | Keep the old data |
| Stale keys or values | Possible, needs `Object.hasOwn` guards | Not possible, the pipeline reads each pair once |
| Key order after renaming | Renamed keys move to the end | Order follows the entries array, which you control |
| Memory | No second object | A temporary array plus a new object |
| Frozen or sealed objects | Fails, and throws in strict mode | Works |
| Engine performance | `delete` can push an object into a slower internal representation | New objects usually keep a stable shape |
Mutate in place when other code holds a reference and must see the change, for example a shared config object, or when the object is large and copying it matters. Build a new object for everything else, especially in code that treats data as immutable, such as React state, Redux reducers, or function arguments you don't own.
Summary of Behaviors
| Loop style | Deleted key not yet visited | Key added during loop | Value changed during loop |
|---|---|---|---|
| `for...of Object.keys(obj)` | Still visited, `obj[key]` is `undefined` | Not visited | `obj[key]` shows the new value |
| `for...of Object.entries(obj)` | Still visited with its old value | Not visited | Destructured value is stale |
| `for...of Object.values(obj)` | Old value still visited | Not visited | Value is stale |
| `for...in obj` | Skipped, guaranteed | Unspecified | `obj[key]` shows the new value |
| `for...of map` | Skipped | Visited | Current value |
Exercise
What does this code print, and why? const prices = { a: 10, b: 20, c: 30 }; for (const [key, price] of Object.entries(prices)) { if (key === 'a') prices.c = 0; console.log(key, price, prices[key]); }
Show answer
It prints "a 10 10", "b 20 20", then "c 30 0". Object.entries copied the pair ['c', 30] before the loop began, so the destructured price stays 30. Reading prices[key] reads the object directly and sees the updated value 0.
Exercise
A function receives a user object and must return it without any properties whose keys start with an underscore. Other parts of the app hold references to the original object and expect it unchanged. Write the function.
Show answer
Build a new object so the original is untouched: const stripPrivate = (user) => Object.fromEntries(Object.entries(user).filter(([key]) => !key.startsWith(''))); For example, stripPrivate({ name: 'Ada', token: 'x' }) returns { name: 'Ada' }, and the original still has _token.
Exercise
This loop is meant to remove each key whose "pair" key is also present (removing 'x' removes 'y'), and to log the keys it keeps. Why does it log a key it already removed, and how do you fix it? const pairs = { x: 'y', y: 'x', z: 'w' }; for (const key of Object.keys(pairs)) { delete pairs[pairs[key]]; console.log('kept', key); }
Show answer
The snapshot ['x', 'y', 'z'] still contains 'y' after the first pass deletes pairs.y, so the loop logs "kept y" for a key that is gone. Reading pairs['y'] also returns undefined, so delete pairs[undefined] runs with no effect. Add "if (!Object.hasOwn(pairs, key)) continue;" as the first line of the body. With the guard, the loop logs "kept x" and "kept z" and leaves { x: 'y', z: 'w' }.