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 collections of key-value pairs. They model real-world entities and are the foundation of almost everything in JavaScript — including arrays, functions, and the DOM.
const person = {
name: "Alice",
age: 30,
isEmployed: true,
};
Each key-value pair is called a property. Keys are strings (or Symbols), and values can be any type — including other objects or functions.
console.log(person.name); // "Alice" (dot notation)
console.log(person["age"]); // 30 (bracket notation)
const key = "isEmployed";
console.log(person[key]); // true (dynamic key lookup)
Use dot notation by default. Use bracket notation when the key is stored in a variable or contains special characters.
const car = { make: "Toyota", model: "Corolla" };
car.year = 2020; // add a new property
car.model = "Camry"; // update an existing property
delete car.year; // remove a property
When a property's value is a function, it is called a method:
const calculator = {
value: 0,
add(n) {
this.value += n;
return this;
},
subtract(n) {
this.value -= n;
return this;
},
result() {
return this.value;
},
};
console.log(calculator.add(10).subtract(3).result()); // 7
The this keyword inside a method refers to the object the method was called on.
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 30
// Rename while destructuring
const { name: fullName } = person;
console.log(fullName); // "Alice"
// Default values
const { role = "user" } = person;
console.log(role); // "user" (property does not exist on person)
const defaults = { theme: "light", language: "en", fontSize: 14 };
const userPrefs = { theme: "dark", fontSize: 16 };
// Merge objects — later properties win
const config = { ...defaults, ...userPrefs };
// { theme: "dark", language: "en", fontSize: 16 }
// Copy an object
const copy = { ...person };
const scores = { Alice: 95, Bob: 87, Carol: 92 };
// for...in — iterates over keys
for (const key in scores) {
console.log(key + ": " + scores[key]);
}
// Object.keys, Object.values, Object.entries
Object.keys(scores); // ["Alice", "Bob", "Carol"]
Object.values(scores); // [95, 87, 92]
Object.entries(scores); // [["Alice", 95], ["Bob", 87], ["Carol", 92]]
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.