Sub topic 5
Adding, Updating, and Deleting Properties
This chapter assumes you can create object literals and read properties with dot and bracket notation. You should also know the difference between let and const. Here you will change objects after they exist: add new properties, overwrite existing ones, and remove them.
Assignment Adds or Updates
JavaScript objects are open by default. Assigning to a property that does not exist creates it. Assigning to one that does exist replaces its value. The syntax is the same for both.
const book = { title: "Dune" };
book.author = "Frank Herbert"; // adds a new property
book["year"] = 1965; // adds, using bracket notation
book.title = "Dune Messiah"; // updates an existing property
const field = "pages";
book[field] = 256; // adds, with a key held in a variable
console.log(book);
// { title: "Dune Messiah", author: "Frank Herbert", year: 1965, pages: 256 }Bracket notation is required when the key is held in a variable, or when the key is not a valid identifier, such as "first name".
The diagram covers the common case. Setters, read-only properties, and frozen objects change this behavior. Later chapters cover those.
`const` Does Not Freeze the Object
const stops you from rebinding the variable. It does not stop you from changing the object the variable points to.
const settings = { theme: "dark" };
settings.theme = "light"; // fine: mutating the object
settings.fontSize = 14; // fine: adding a property
// settings = {}; // TypeError: Assignment to constant variable.
console.log(settings); // { theme: "light", fontSize: 14 }Removing Properties with `delete`
The delete operator removes a property from an object entirely. It returns true if the property is gone afterward, and that includes the case where it never existed.
const user = { name: "Sam", email: "[email protected]", temp: 42 };
console.log(delete user.temp); // true
console.log(delete user["email"]); // true
console.log(delete user.nothing); // true: nothing to remove
console.log(user); // { name: "Sam" }Setting a property to undefined does something different from deleting it. The key stays on the object and still shows up when you list its keys:
const a = { x: 1 };
const b = { x: 1 };
a.x = undefined;
delete b.x;
console.log(Object.keys(a)); // ["x"]
console.log(Object.keys(b)); // []The next chapter covers how to test for a property that exists but holds undefined.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Typo in a property name, such as `user.emial = "..."` | A new property is created silently and no error is raised | Use consistent names; linters and TypeScript catch these |
| `delete` on an array element | The element is removed but `length` stays the same, leaving a hole | Use `splice` to remove array items |
| `delete` on a variable | Has no effect; strict mode reports a SyntaxError | `delete` only works on properties |
| Deleting a built-in, such as `delete Math.PI` | Returns `false`; strict mode throws a TypeError | Some properties are non-configurable and cannot be removed |
const arr = [10, 20, 30];
delete arr[1];
console.log(arr.length); // 3
console.log(arr[1]); // undefined: a hole, not a removed slot
const arr2 = [10, 20, 30];
arr2.splice(1, 1);
console.log(arr2); // [10, 30]Exercise
After running const p = { a: 1, b: 2 }; p.b = undefined; p.c = 3; delete p.a;, what does Object.keys(p) return, and why is "b" included?
Show answer
It returns ["b", "c"]. delete removed a. Assigning undefined to b changed its value but kept the key, and c was added by assignment.
Exercise
Why does const cfg = {}; cfg.debug = true; run without an error, while cfg = { debug: true }; throws?
Show answer
const blocks reassigning the variable cfg. It does not block changes to the object that cfg refers to, so adding a property is allowed but rebinding the variable is not.