Object literals
const user = {
id: 1,
name: 'Ahbab',
email: 'a@example.com',
greet() {
return `Hi, ${this.name}!`;
}
};
Access & computed properties
user.name; // dot
user['email']; // bracket (useful with dynamic keys)
const key = 'id';
user[key]; // 1
Destructuring & defaults
const { name, email = 'n/a' } = user;
const { id: userId } = user; // rename
Copy/merge (shallow)
const a = { x: 1, y: 2 };
const b = { y: 3, z: 4 };
const merged = { ...a, ...b }; // { x:1, y:3, z:4 }
const copy = { ...a }; // { x:1, y:2 }
const assigned = Object.assign({}, a, b); // same idea
Practice
- Create a
courseobject withtitle,hours, andtags. - Write a method on it that returns a summary string.
- Use destructuring to pull out
titleandhours.
Next up
Quick Check
Which operator checks whether a property exists on an object?