JavaScript Objects
Objects are used to store keyed collections of data. An object is a collection of properties (key-value pairs), where values can be data or functions (methods).
Creating an Object
Object Literal
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false,
};
console.log(person);
console.log(person.firstName); // dot notation
console.log(person["age"]); // bracket notationAccessing Properties
| Notation | Syntax | Use When |
|---|---|---|
| Dot | obj.propertyName | Key is a valid identifier |
| Bracket | obj["key"] | Key has spaces / is dynamic |
Dot vs Bracket Notation
const car = { make: "Toyota", model: "Camry", year: 2022 };
console.log(car.make); // Toyota
console.log(car["model"]); // Camry
// Dynamic key with bracket notation:
let prop = "year";
console.log(car[prop]); // 2022Adding and Modifying Properties
Mutating Objects
const user = { name: "Alice" };
user.age = 28; // add new property
user.name = "Alicia"; // modify existing property
console.log(user); // { name: "Alicia", age: 28 }
delete user.age; // remove a property
console.log(user); // { name: "Alicia" }Methods — Functions Inside Objects
A method is a function stored as an object property. Inside methods, this refers to the object.
Object Methods
const calculator = {
value: 0,
add(n) { this.value += n; return this; },
subtract(n) { this.value -= n; return this; },
result() { return this.value; },
};
calculator.add(10).add(5).subtract(3);
console.log(calculator.result()); // 12Looping Over an Object
for...in and Object Helpers
const scores = { math: 95, english: 88, science: 92 };
for (let subject in scores) {
console.log(subject + ": " + scores[subject]);
}
console.log(Object.keys(scores)); // ["math", "english", "science"]
console.log(Object.values(scores)); // [95, 88, 92]
console.log(Object.entries(scores)); // [["math",95], ...]Nested Objects
Nested Objects
const company = {
name: "Acme",
address: {
street: "123 Main St",
city: "Springfield",
},
employees: ["Alice", "Bob", "Carol"],
};
console.log(company.name);
console.log(company.address.city);
console.log(company.employees[0]);📝 Note: Objects declared with const can still have their properties changed — const only prevents reassigning the variable itself.
Exercise:
How do you access a property called 'name' on an object called person?