Objects: Creating, Accessing, and Nesting
An object holds related data under one name. Access properties with dot or bracket notation, and know that objects are copied by reference, not by value.
Objects store key-value pairs. Dot notation for known keys, bracket notation for dynamic keys. Assigning an object to another variable copies the reference, not the data. Use spread for real copies.
EXERCISE
1Objects: Your First Data Structure
An object is a container that holds related data under one name. Instead of creating five separate variables for a user, you create one object with five properties.
An array holds a list of similar things. An object describes one thing with several named attributes. The difference is how you reach the values: by position in an array, by name in an object.
const user = {
name: "Sara",
age: 28,
city: "Dubai",
isActive: true,
};
console.log(user.name); // "Sara"
Each line inside the braces is a property: a key on the left, a value on the right. Keys are strings, even when you write them without quotes, and values can be anything at all, including other objects and functions.
Two ways to reach a property, and they are not interchangeable:
console.log(user.city); // "Dubai"
console.log(user["city"]); // "Dubai"
const key = "isActive";
console.log(user[key]); // true
console.log(user.key); // undefined
The last line is the point. Dot notation takes the name literally, so user.key looks for a property actually called key. Bracket notation evaluates what is inside it, so user[key] looks up "isActive". When the property name is in a variable, brackets are the only option.
Brackets are also required for names that are not valid identifiers:
const config = { "max-retries": 3, "2fa": true };
console.log(config["max-retries"]); // 3
console.log(config["2fa"]); // true
Objects are mutable, and adding a property is just assigning to it:
const car = { brand: "Toyota", year: 2023 };
car.color = "blue";
delete car.year;
console.log(car); // { brand: "Toyota", color: "blue" }
Note that car was declared const and all of this is legal. const prevents the name being pointed at a different object; it says nothing about the contents. Reassigning car to something else would throw, but changing what is inside it does not.
A missing property is undefined, not an error:
console.log(user.email); // undefined
This is the same undefined from unit 2, and it means a typo in a property name fails silently. user.nmae gives you undefined rather than telling you the name is wrong, and the failure appears wherever that value is finally used.
EXERCISE
2Nested Objects and Objects as References
Objects can contain other objects, creating rich data structures. But beware: when you copy an object, you copy the reference, not the data.
Real data nests. A user has an address, an address has a city, and reaching through those levels is just repeating the same property access.
const student = {
name: "Ali",
scores: { math: 95, english: 88 },
address: { city: "London", country: "UK" },
};
console.log(student.scores.math); // 95
console.log(student.address.city); // "London"
Each dot moves one level in. The risk is that a missing level throws rather than returning undefined:
console.log(student.contact.email);
// TypeError: Cannot read properties of undefined (reading 'email')
student.contact is undefined, and reading a property of undefined is an error. Optional chaining stops at the first missing link instead:
console.log(student.contact?.email); // undefined
The more important behaviour is that objects are held by reference:
const original = { name: "Sara", age: 28 };
const copy = original;
copy.age = 99;
console.log(original.age); // 99
copy = original did not duplicate anything. Both names point at the same object, so there is only one age and both see the change. This is the single most common source of "I changed one thing and something else broke".
Copying requires asking for a copy:
const original = { name: "Sara", age: 28 };
const copy = { ...original };
copy.age = 99;
console.log(original.age); // 28
console.log(copy.age); // 99
The spread builds a new object with the same properties, so the two are now independent.
That copy is shallow, and the distinction matters as soon as the object nests:
const user = { name: "Ali", address: { city: "London" } };
const shallow = { ...user };
shallow.address.city = "Paris";
console.log(user.address.city); // "Paris"
The top level was copied, so shallow.name is independent. But address is itself an object, and what was copied is the reference to it, which both now share. For a deep copy use structuredClone(user), which duplicates every level.
EXERCISE
3Methods: Functions Inside Objects
When a function lives inside an object, it is called a method. Methods let objects do things, not just hold data.
A function stored on an object is called a method. It is an ordinary function on an ordinary property, and the only thing that makes it special is what this refers to when you call it.
const account = {
owner: "Sara",
balance: 100,
describe() {
return this.owner + " has " + this.balance;
},
};
console.log(account.describe()); // "Sara has 100"
describe() is shorthand for describe: function () {}. Inside it, this is whatever object the method was called on, which here is account, because the call was written account.describe().
That last clause is the whole rule, and it has a consequence people meet the hard way:
const fn = account.describe;
console.log(fn());
// TypeError: Cannot read properties of undefined (reading 'owner')
Nothing about the function changed. What changed is the call: there is no object before the dot, so there is no receiver, and this is undefined. This happens constantly when a method is passed as a callback:
setTimeout(account.describe, 100); // same failure, 100ms later
Two fixes. bind fixes the receiver permanently:
const bound = account.describe.bind(account);
console.log(bound()); // "Sara has 100"
Or wrap the call so the method is still invoked on the object:
setTimeout(() => account.describe(), 100); // "Sara has 100"
Methods that change state are where the object earns its keep:
const account = {
balance: 100,
deposit(amount) {
if (amount <= 0) return this.balance;
this.balance += amount;
return this.balance;
},
};
console.log(account.deposit(50)); // 150
console.log(account.deposit(-10)); // 150, rejected
The rule about what a valid deposit is lives next to the data it protects.
Pro Tip: Do not write a method as an arrow function on an object literal. An arrow has no
thisof its own and takes it from the surrounding scope, which is not the object, sothis.ownerwill beundefinedno matter how you call it.
