JavaScript Lesson 9: Objects
Objects store key-value pairs and are the most fundamental data structure in JavaScript. Everything in JS is an object or acts like one.
Creating Objects
const person = {
name: "Alice",
age: 30,
city: "London",
isStudent: false
};
// Access values
console.log(person.name); // Alice (dot notation)
console.log(person["age"]); // 30 (bracket notation)
// Bracket notation for dynamic keys
const key = "city";
console.log(person[key]); // London
Modifying Objects
const car = { brand: "Toyota", year: 2020 };
// Add a property
car.color = "blue";
// Update a property
car.year = 2024;
// Delete a property
delete car.color;
// Check if property exists
console.log("brand" in car); // true
console.log("color" in car); // false
Object Methods
const player = {
name: "Alice",
score: 0,
level: 1,
addPoints(points) {
this.score += points;
},
levelUp() {
this.level++;
console.log(`${this.name} is now level ${this.level}!`);
},
getInfo() {
return `${this.name} | Score: ${this.score} | Level: ${this.level}`;
}
};
player.addPoints(100);
player.levelUp();
console.log(player.getInfo());
// Alice is now level 2!
// Alice | Score: 100 | Level: 2
Object Utilities
const scores = { alice: 95, bob: 87, charlie: 92 };
// Get all keys
Object.keys(scores) // ["alice", "bob", "charlie"]
// Get all values
Object.values(scores) // [95, 87, 92]
// Get key-value pairs
Object.entries(scores) // [["alice",95], ["bob",87], ...]
// Merge objects
const defaults = { theme: "dark", lang: "en" };
const user = { lang: "fr", name: "Alice" };
const merged = { ...defaults, ...user };
// { theme: "dark", lang: "fr", name: "Alice" }
🏋️ Practice Task
Create an inventory system object with: items array, addItem(name, price, qty) method, removeItem(name) method, getTotalValue() method (sum of price*qty for all items), and listItems() method. Test with 3 items.
💡 Hint: Store items as array of objects: {name, price, qty}. getTotalValue uses reduce or a for loop.