JavaScript objects stay open for business. You can add properties long after the object was created, you can change them, you can rename them, and you can remove them. The syntax is easy. The decisions are not, especially when the value that you are storing is itself an object.
The previous lesson in this module covered "Objects: Properties, Access and Mutability", and the next lesson in this module is about "Object References vs a Real Copy".
How do I add a new property to an object?
You assign to a property that does not exist yet, and it is created. There are two spellings, and both of them work on any plain object.
const user = { name: 'Ada' };
user.role = 'engineer';
user['city'] = 'London';
console.log(user);
// { name: 'Ada', role: 'engineer', city: 'London' }
Use dot notation for the names that you control, and bracket notation for names that contain spaces or hyphens, or names that arrived from somewhere else. Either way the key is added to the end of the object's key order, and that matters later if you save the object as JSON. The detail worth remembering is that this changes the object in place. Your variable still points at the same object, so anyone else who holds a reference sees the new key as well.
How do I create a key from a variable?
Sometimes the name of the key is only known at runtime, such as a form field name, a table column, or a route parameter. Square brackets that contain an expression tell JavaScript to use the value of that expression as the property name.
const field = 'emailAddress';
const profile = { [field]: '[email protected]' };
console.log(profile.emailAddress); // [email protected]
console.log(profile[field]); // [email protected]
Without the computed brackets you would get an object with a key that is literally called field. You can mix computed keys and plain keys in the same literal, for example { [field]: value, id: 1 }. The same syntax reads from an object as well, which is why profile[field] returns the stored address and not undefined.
How do I update several properties at once?
When you want to change a handful of properties and keep the rest, the safe pattern is to build a new object out of the old one plus your changes. The object spread does that in a single expression.
const defaults = { theme: 'light', fontSize: 14 };
const userPrefs = { theme: 'dark' };
const merged = { ...defaults, ...userPrefs };
console.log(merged); // { theme: 'dark', fontSize: 14 }
const assigned = Object.assign({}, defaults, userPrefs);
console.log(assigned); // { theme: 'dark', fontSize: 14 }
The order matters, because the spread that comes last wins. Here the user's theme of dark overwrites the default, while fontSize survives because the user never mentioned it. Object.assign does the same job with an explicit target. The spread version is shorter, and because the target is a fresh literal it cannot accidentally modify its first argument. One caveat to carry forward is that the spread copies only one level deep, so if a property holds a nested object, then both copies still point at that same nested object.
How do I remove a key, and how do I rename one?
The delete operator removes a key from an object outright. There is no built-in rename, because a rename is really a delete followed by an add.
const settings = { theme: 'dark', legacyFlag: true };
delete settings.legacyFlag;
console.log(settings); // { theme: 'dark' }
console.log('legacyFlag' in settings); // false
const original = { userName: 'ada', role: 'admin' };
const renamed = { ...original };
renamed.username = renamed.userName;
delete renamed.userName;
console.log(renamed); // { role: 'admin', username: 'ada' }
delete is a statement rather than a function, so it takes no parentheses. It reports success whether or not the key was actually there, which means that it is useless as an existence test. Use Object.hasOwn for that instead. The rename above works on a copy, so the original object keeps its original key while the new object has the new one.
How do I build an object from a list of pairs?
Object.fromEntries takes a list of key-value pairs, where each pair is an array of two elements, and it returns an object built from them. It is the standard way to turn data that is shaped like an array into a keyed structure.
const fields = ['name', 'role'];
const values = ['Ada', 'admin'];
const pairs = [];
for (let index = 0; index < fields.length; index++) {
pairs.push([fields[index], values[index]]);
}
const user = Object.fromEntries(pairs);
console.log(user); // { name: 'Ada', role: 'admin' }
The loop builds the pairs from two parallel arrays, which is a common shape when you are turning a table of form inputs into a payload. The reverse conversion exists as well. Object.entries takes an object and hands back the pairs, and that is the subject of the iteration lesson later in this module.
How do I check whether a key exists?
Two tools answer that question, and they differ in a way that matters. The in operator checks the object and its prototype chain, so it reports true for inherited properties such as toString. Object.hasOwn only reports true for properties that the object itself owns.
const post = { title: 'Hello' };
console.log('title' in post); // true
console.log('author' in post); // false
console.log(Object.hasOwn(post, 'title')); // true
For plain data objects the difference rarely shows up. It matters the moment you work with class instances, or with objects created through Object.create. Object.hasOwn is the newer and clearer spelling, so prefer it unless you specifically want inherited properties to count.
What is worth remembering about object keys?
| Operation | Syntax | Note |
|---|---|---|
| Add | obj.key = value | Changes the object in place |
| Add with a dynamic key | obj[key] = value | Works with any string |
| Create with a computed key | { [key]: value } | Inside an object literal |
| Update several | { ...obj, ...changes } | Later wins, and only one level deep |
| Remove | delete obj.key | Drops the key entirely |
| Rename | copy, add, delete | No built-in rename exists |
| Build from pairs | Object.fromEntries(pairs) | Each pair is [key, value] |
| Test existence | Object.hasOwn(obj, key) | in also matches inherited keys |
Try it yourself: write a file called keys.js and start with const settings = { theme: 'light', fontSize: 14, language: 'en' };. Add a zoom property of 100 with dot notation, and add a timezone property by using a variable that holds the text 'timezone' with bracket notation. Then print the object. Next, build an updated copy with the spread syntax that changes the theme to dark and leaves everything else alone, and print both objects to show that the original is untouched. Rename language to locale on that copy by adding the new key and deleting the old one. Finally, delete the zoom property, print the result, and check with Object.hasOwn whether timezone is still there.