You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Objects are the most important data structure in JavaScript. They store collections of key-value pairs and are the foundation of almost everything in the language — from simple data containers to complex class instances.
The most common way to create an object:
const person = {
firstName: "Alice",
lastName: "Smith",
age: 30,
isStudent: false,
};
const obj = {
"full name": "Alice Smith",
"data-id": 42,
};
console.log(person.firstName); // "Alice"
console.log(person.age); // 30
console.log(person["lastName"]); // "Smith"
const key = "age";
console.log(person[key]); // 30
console.log(obj["full name"]); // "Alice Smith"
const car = { make: "Toyota" };
// Add a property
car.model = "Camry";
car.year = 2024;
// Modify a property
car.year = 2025;
// Delete a property
delete car.year;
console.log(car); // { make: "Toyota", model: "Camry" }
When a variable name matches the property name:
const name = "Alice";
const age = 30;
// Instead of { name: name, age: age }
const person = { name, age };
console.log(person); // { name: "Alice", age: 30 }
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
};
console.log(calculator.add(5, 3)); // 8
const field = "email";
const user = {
[field]: "alice@example.com",
};
console.log(user.email); // "alice@example.com"
| Method | Returns |
|---|---|
Object.keys(obj) | Array of keys |
Object.values(obj) | Array of values |
Object.entries(obj) | Array of [key, value] pairs |
const scores = { maths: 90, english: 85, science: 92 };
Object.keys(scores); // ["maths", "english", "science"]
Object.values(scores); // [90, 85, 92]
Object.entries(scores);
// [["maths", 90], ["english", 85], ["science", 92]]
// Iterating with for...of and destructuring
for (const [subject, score] of Object.entries(scores)) {
console.log(subject + ": " + score);
}
Extract properties into variables:
const user = { name: "Alice", age: 30, city: "London" };
const { name, age, city } = user;
console.log(name); // "Alice"
console.log(city); // "London"
// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"
// Default values
const { country = "UK" } = user;
console.log(country); // "UK"
// Nested destructuring
const order = {
product: { name: "Laptop", price: 999 },
quantity: 2,
};
const { product: { name: productName, price } } = order;
console.log(productName); // "Laptop"
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.