Object Destructuring
Object Destructuring 📦
Why this matters: most real data comes back as big nested objects (API responses, config, options). Destructuring lets you pull out just the pieces you care about, with clear variable names and minimal repetition.
Destructuring lets you extract values from objects into variables in a single line. It's like unpacking a box!
Why Use Destructuring?
The Old Way (Repetitive)
const person = { name: "Alex", age: 25, city: "London" };
const name = person.name;
const age = person.age;
const city = person.city;
// Repeating "person" is annoying!
The New Way (Clean)
const { name, age, city } = person;
// All three variables created in one line!
console.log(name); // "Alex"
console.log(age); // 25
console.log(city); // "London"
How It Works
const { propertyName } = object;
// ↑ Creates a variable with same name as property
Real-World Use Case: API Response
// Typical API response
const response = {
user: { name: "Alex", email: "alex@email.com" },
token: "abc123",
status: "success"
};
// Extract what you need
const { user, token } = response;
console.log(user.name); // "Alex"
console.log(token); // "abc123"
Renaming Variables
What if the property name conflicts with another variable?
const person = { name: "Alex" };
const name = "Different Name"; // Already exists!
// Rename while destructuring
const { name: userName } = person;
console.log(userName); // "Alex"
Default Values
const person = { name: "Alex" };
const { name, age = 18 } = person;
console.log(age); // 18 (default since not in object)
Your Turn!
Extract title and author from the book object using destructuring.