Episode 28 of 46
Introduction to Objects
Learn what objects are and how they store data as key-value pairs.
Objects are collections of key-value pairs. They are the most important data structure in JavaScript — almost everything in JS is an object.
Creating Objects
let person = {
name: "Alice",
age: 25,
city: "London",
isStudent: true
};
Accessing Properties
// Dot notation (preferred)
console.log(person.name); // "Alice"
console.log(person.age); // 25
// Bracket notation (for dynamic keys)
console.log(person["city"]); // "London"
let key = "name";
console.log(person[key]); // "Alice"
Modifying Objects
// Change a property
person.age = 26;
// Add a new property
person.email = "alice@example.com";
// Delete a property
delete person.isStudent;
Objects with Methods
let calculator = {
add: function(a, b) {
return a + b;
},
// Shorthand method syntax
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(3, 5)); // 8
console.log(calculator.subtract(10, 4)); // 6
Nested Objects
let user = {
name: "Alice",
address: {
street: "123 Main St",
city: "London",
country: "UK"
}
};
console.log(user.address.city); // "London"
Checking Properties
"name" in person; // true
person.hasOwnProperty("email"); // true
Object.keys(person); // ["name", "age", "city", "email"]
Object.values(person); // ["Alice", 26, "London", "alice@..."]