Sub topic 5
Adding, Updating, and Deleting Properties
JavaScript objects are mutable by default. You can add a property to an existing object, change its value, or remove it at any time, and none of these steps needs a special API. That flexibility leads to some quiet bugs: assignments that do nothing, deletes that report success without removing anything, and counters that turn into NaN. This chapter covers how each operation works and where it goes wrong.
The chapter assumes you can create object literals and read properties with dot and bracket notation, as covered in earlier chapters. It also assumes you know basic JavaScript syntax, functions, and arrays, and that you can run code in Node.js or a browser console.
Adding and Updating with Assignment
JavaScript uses one syntax for both adding and updating a property. If the object has no property with that key, assignment creates one. If it already has one, assignment replaces the value.
const user = { name: "Lin" };
user.email = "[email protected]"; // adds a new property
user.name = "Lin Wei"; // updates an existing property
const field = "age";
user[field] = 34; // bracket notation with a dynamic key
console.log(user); // { name: 'Lin Wei', email: '[email protected]', age: 34 }Use dot notation when you know the key when you write the code and it is a valid identifier. Use bracket notation when the key comes from a variable, or when it contains spaces or hyphens, like "top speed".
Keys Are Converted to Strings
Bracket notation accepts any value as a key. Anything that is not a symbol is converted to a string first, which can cause collisions you did not expect.
const scores = {};
scores[1] = "a";
scores["1"] = "b"; // same key as scores[1]
console.log(Object.keys(scores)); // [ '1' ]
const k1 = { id: 1 };
const k2 = { id: 2 };
const lookup = {};
lookup[k1] = "first";
lookup[k2] = "second"; // both keys become "[object Object]"
console.log(lookup[k1]); // "second"
console.log(Object.keys(lookup)); // [ '[object Object]' ]If you need objects as keys, use a Map. A plain object cannot tell two object keys apart.
Common Update Patterns and Their Traps
Compound Assignment on Missing Properties
Reading a missing property gives undefined, and undefined + 1 is NaN. This breaks the obvious way to write a counter:
const words = ["a", "b", "a"];
const bad = {};
for (const w of words) bad[w] += 1;
console.log(bad); // { a: NaN, b: NaN }
const counts = {};
for (const w of words) counts[w] = (counts[w] ?? 0) + 1;
console.log(counts); // { a: 2, b: 1 }The nullish coalescing operator ?? falls back to 0 only when the value is undefined or null. A stored 0 is kept.
Writing into Nested Objects
Assigning to a.b.c first reads a.b. If a.b is undefined, the write throws, because you cannot set a property on undefined.
const settings = {};
try {
settings.theme.color = "dark";
} catch (e) {
console.log(e.name); // "TypeError"
}
settings.theme ??= {}; // create the inner object only if missing
settings.theme.color = "dark";
settings.theme ??= {}; // no effect: theme already exists
console.log(settings); // { theme: { color: 'dark' } }Logical assignment operators (??=, ||=, &&=) only write when their condition holds. x.p ??= v assigns when x.p is null or undefined. x.p ||= v also overwrites 0, "", and false, which is often a bug.
Adding Several Properties at Once
Object.assign(target, ...sources) copies the own enumerable properties of each source onto the target. It changes the target and returns it. Spread syntax builds a new object and leaves the original alone.
const post = { id: 1, title: "Draft" };
Object.assign(post, { views: 0, title: "Edited" }); // mutates post
console.log(post); // { id: 1, title: 'Edited', views: 0 }
const renamed = { ...post, title: "Final" }; // new object
console.log(post.title, renamed.title); // Edited FinalWhen you spread, properties listed later overwrite earlier ones. Put the defaults first and the overrides after them: { ...defaults, ...options }.
What Assignment Actually Does
Assignment does not always create a property on the object you wrote to. Before it writes, the engine checks the object's own property, then the prototype chain, then whether the object accepts new properties. This diagram shows the decision for obj.key = value. Later chapters cover prototypes, descriptors, setters, and locking in detail. For now, note the places where assignment can fail.
The most common case is the inherited writable property. Assignment creates a new own property that shadows the inherited one, and the prototype does not change:
const base = { greeting: "hi" };
const child = Object.create(base);
child.greeting = "hello"; // creates an own property on child
console.log(child.greeting, base.greeting); // hello hiDeleting Properties
The delete operator removes an own property from an object. It returns true if the property is gone after the operation and false if it could not be removed.
const item = { id: 1, draft: true, note: undefined };
console.log(delete item.draft); // true: removed
console.log(delete item.missing); // true: nothing to remove, still "succeeds"
console.log(Object.keys(item)); // [ 'id', 'note' ]Because true means "it is not there now," the return value does not tell you whether the property existed. Check for it first if that matters. The next chapter covers how.
Deleting Is Not the Same as Setting undefined
item.note has the value undefined, but note is still a key. Setting a property to undefined leaves the key in place for Object.keys, for...in, the in operator, and spread. delete removes the key.
| Operation | Key still listed? | `obj.key` reads | `"key" in obj` |
|---|---|---|---|
| `obj.key = undefined` | yes | `undefined` | `true` |
| `delete obj.key` | no | `undefined` (or inherited value) | `false` unless inherited |
delete Only Touches Own Properties
delete never walks the prototype chain. If you delete a shadowing property, the inherited value shows through again. Deleting a second time does nothing to the prototype.
const base = { greeting: "hi" };
const child = Object.create(base);
child.greeting = "hello";
delete child.greeting;
console.log(child.greeting); // "hi": the inherited value is visible again
delete child.greeting; // returns true, base is untouched
console.log(base.greeting); // "hi"When delete Fails
Some properties are non-configurable, which means they cannot be removed. Math.PI is one of them. In sloppy mode, delete returns false. In strict mode, it throws. ES modules and class bodies always run in strict mode.
console.log(delete Math.PI); // false (in sloppy-mode scripts)
function strictDelete() {
"use strict";
try {
delete Math.PI;
} catch (e) {
console.log(e.name); // "TypeError"
}
}
strictDelete();delete also does not work on variables. In sloppy mode, delete someVariable returns false. In strict mode, it is a SyntaxError.
Deleting Array Elements Leaves Holes
Arrays are objects, so delete arr[i] removes the element's property. It does not shift the remaining elements or change length.
const arr = [10, 20, 30];
delete arr[1];
console.log(arr.length); // 3
console.log(arr); // [ 10, <1 empty item>, 30 ]
arr.splice(1, 1); // remove one element at index 1
console.log(arr); // [ 10, 30 ]Use splice to remove elements in place, or filter when you want a new array.
Removing Without Mutating
Code that shares objects, such as state in UI frameworks, usually needs a new object without a key instead of changing the original. Rest destructuring does this. A later chapter explains destructuring in full.
const original = { id: 1, draft: true, title: "Post" };
const { draft, ...published } = original;
console.log(published); // { id: 1, title: 'Post' }
console.log(original); // unchanged: { id: 1, draft: true, title: 'Post' }Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| Counter values are `NaN` | `obj[k] += 1` on a missing key | `obj[k] = (obj[k] ?? 0) + 1` |
| `TypeError: Cannot set properties of undefined` | Writing through a missing intermediate object | `obj.a ??= {}` first |
| Two object keys overwrite each other | Keys converted to `"[object Object]"` | Use a `Map` |
| Key still appears in `Object.keys` | Set to `undefined` instead of deleted | Use `delete` or rest destructuring |
| Array length unchanged after delete | `delete` leaves a hole | Use `splice` or `filter` |
| Caller's object changed unexpectedly | Function mutated its argument | Return a new object with spread |
Exercise
What does this code log, and why? const o = {}; o[true] = 1; o["true"] += 1; delete o.missing; console.log(Object.keys(o), o.true);
Show answer
It logs [ 'true' ] 2. The key true is converted to the string "true", so o["true"] refers to the same property and += 1 turns 1 into 2. delete o.missing returns true and does nothing, because there is no such property.
Exercise
Write a function setPath(obj, keys, value) that sets a nested value, creating missing intermediate objects, so that setPath({}, ["a", "b", "c"], 5) returns { a: { b: { c: 5 } } }.
Show answer
function setPath(obj, keys, value) { let cur = obj; for (const k of keys.slice(0, -1)) { cur[k] ??= {}; cur = cur[k]; } cur[keys[keys.length - 1]] = value; return obj; } The loop uses ??= to create each missing level without overwriting existing objects, then assigns the last key.
Exercise
Given const base = { x: 1 }; const c = Object.create(base); c.x = 2; delete c.x; delete c.x; what is c.x, base.x, and the return value of the second delete?
Show answer
c.x is 1, base.x is 1, and the second delete returns true. The first delete removes c's own shadowing property, so the inherited x shows through again. The second delete finds no own property and returns true without touching base.