Arrays and ObjectsLesson 4.2
JavaScript Objects: Properties, Methods, and Patterns
object literals, accessing properties, methods, this, computed properties, object destructuring, Object.keys, Object.values, Object.entries, spread with objects
JavaScript Objects: Properties, Methods, and Patterns
Objects are the core data structure of JavaScript. Almost everything in JavaScript is an object or can behave like one. An object is a collection of key-value pairs, where keys are strings (or Symbols) and values can be any data type.
Creating Objects
const product = {
name: 'Laptop',
price: 999,
inStock: true,
specs: {
ram: '16GB',
storage: '512GB SSD'
}
};
console.log(product.name); // 'Laptop'
console.log(product['price']); // 999
console.log(product.specs.ram); // '16GB'Object Methods and this
const person = {
firstName: 'Alice',
lastName: 'Johnson',
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.getFullName()); // 'Alice Johnson'Object Destructuring
Destructuring lets you extract properties into variables with a clean, readable syntax.
const { name, price, inStock } = product;
console.log(name); // 'Laptop'
console.log(price); // 999
// With renaming and defaults
const { name: productName, discount = 0 } = product;
console.log(productName); // 'Laptop'
console.log(discount); // 0Object Utilities
const car = { make: 'Toyota', model: 'Camry', year: 2022 };
console.log(Object.keys(car)); // ['make', 'model', 'year']
console.log(Object.values(car)); // ['Toyota', 'Camry', 2022]
console.log(Object.entries(car)); // [['make','Toyota'], ['model','Camry'], ['year',2022]]Spreading and Merging Objects
const defaults = { theme: 'light', language: 'en', notifications: true };
const userPrefs = { theme: 'dark', language: 'fr' };
const settings = { ...defaults, ...userPrefs };
console.log(settings);
// { theme: 'dark', language: 'fr', notifications: true }