Accessing, Adding and Updating Properties
Reading, writing, adding and deleting properties are the four operations every object supports, and each has a detail worth knowing.
Dot and bracket notation both read and write. A missing property gives undefined, optional chaining stops the crash, and delete removes a key entirely. Keys are always strings underneath.
EXERCISE
1Four Operations on One Object
An object is a set of key-value pairs, and everything you do with one is reading, writing, adding or removing a pair.
All four, in order:
const user = { name: "Ada", age: 36 };
// Read
console.log(user.name); // Ada
// Update an existing key
user.age = 37;
console.log(user.age); // 37
// Add a key that was not there
user.city = "London";
console.log(user); // { name: 'Ada', age: 37, city: 'London' }
// Remove a key entirely
delete user.age;
console.log(user); // { name: 'Ada', city: 'London' }
console.log(user.age); // undefined
Adding and updating look identical, which is the point:
const settings = {};
settings.theme = "dark"; // added
settings.theme = "light"; // updated
console.log(settings); // { theme: 'light' }
// JavaScript does not distinguish. The key either exists or it does not.
delete versus setting to undefined:
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
delete a.y;
b.y = undefined;
console.log(a); // { x: 1 }
console.log(b); // { x: 1, y: undefined }
console.log("y" in a); // false the key is gone
console.log("y" in b); // true the key is there, holding nothing
Checking whether a key exists:
const user = { name: "Ada", nickname: undefined };
console.log(user.nickname); // undefined
console.log("nickname" in user); // true it IS there
console.log("age" in user); // false
console.log(Object.hasOwn(user, "age")); // false
undefined from a property read is ambiguous: the key might be missing, or it might be present and empty. Use in or Object.hasOwn when the difference matters, which it does for configuration objects and for anything where "not set" and "set to nothing" mean different things.
EXERCISE
2Dot Notation and Bracket Notation
Two ways to reach a property, and the choice is forced in two specific situations rather than being a matter of taste.
Dots for ordinary keys, brackets when you have to:
const user = { name: "Ada", "favourite colour": "teal" };
console.log(user.name); // Ada
console.log(user["name"]); // Ada same thing
console.log(user["favourite colour"]); // teal
// console.log(user.favourite colour); // SyntaxError
The important case: a key held in a variable:
const user = { name: "Ada", age: 36 };
const field = "age";
console.log(user[field]); // 36 <- evaluates field first
console.log(user.field); // undefined <- looks for a key called "field"
Which is what makes generic code possible:
const user = { name: "Ada", age: 36, city: "London" };
for (const key of ["name", "city"]) {
console.log(`${key}: ${user[key]}`);
}
// name: Ada
// city: London
function pick(object, keys) {
const result = {};
for (const key of keys) {
result[key] = object[key];
}
return result;
}
console.log(pick(user, ["name", "city"])); // { name: 'Ada', city: 'London' }
Keys are always strings underneath:
const scores = {};
scores[1] = "one";
scores["1"] = "uno";
console.log(scores); // { '1': 'uno' } <- one key, not two
console.log(scores[1]); // uno
// The number 1 was converted to the string "1".
// Only symbols escape this rule.
Computed keys when building an object:
const field = "role";
const user = {
name: "Ada",
[field]: "admin", // the brackets evaluate `field`
};
console.log(user); // { name: 'Ada', role: 'admin' }
Pro Tip: Dot notation asks for a key with that literal spelling; bracket notation works out what is inside the brackets first and asks for that. Almost every "why is this undefined?" moment with objects comes down to using a dot where the key was in a variable, so
user.fieldlooked for a key literally namedfield.
EXERCISE
3Nested Objects and Safe Access
Real data nests several levels deep, and reading through a level that is missing is the most common crash in JavaScript.
Reading down through levels:
const order = {
id: 1,
customer: {
name: "Ada",
address: { city: "London", postcode: "EC1" },
},
};
console.log(order.customer.name); // Ada
console.log(order.customer.address.city); // London
The crash, when a level is missing:
const order = {
id: 2, customer: { name: "Grace" }
};
console.log(order.customer.address); // undefined
console.log(order.customer.address.city);
// TypeError: Cannot read properties of undefined (reading 'city')
The first line is fine. The second asks undefined for a property, and that throws.
Optional chaining, which stops at the first missing level:
console.log(order.customer?.address?.city); // undefined, no crash
// And with a fallback:
console.log(order.customer?.address?.city ?? "Unknown"); // Unknown
It works on arrays and function calls too:
const data = { items: null };
console.log(data.items?.[0]); // undefined
console.log(data.onSave?.()); // undefined, no crash
Writing into a nested object needs the level to exist:
const config = {};
// config.theme.colour = "blue";
// TypeError: Cannot set properties of undefined
config.theme = {}; // create the level first
config.theme.colour = "blue";
console.log(config); // { theme: { colour: 'blue' } }
// Or in one step:
const config2 = {
theme: { colour: "blue" }
};
Pro Tip: Use
?.when a level genuinely might be missing, such as data from an API or a user who may not have filled in an address. Do not scatter it everywhere: a?.on a level that should always exist hides a real bug behind a silentundefined, and you lose the error that would have told you the data was wrong.
