📦 Unpack Like Python
Accessing nested properties? const x = obj.prop.nested? Verbose. Destructuring extracts values from objects and arrays elegantly. One line replaces five.
Object Destructuring
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
address: {
city: 'New York',
country: 'USA'
}
};
// ❌ Old way
const name = user.name;
const age = user.age;
const email = user.email;
// ✅ Destructuring
const { name, age, email } = user;
console.log(name); // 'Alice'
console.log(age); // 30
console.log(email); // 'alice@example.com'
🎯 Advanced Object Destructuring
// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName); // 'Alice'
// Default values
const { name, role = 'guest' } = user;
console.log(role); // 'guest' (not in object)
// Nested destructuring
const { address: { city, country } } = user;
console.log(city); // 'New York'
// Rest operator (collect remaining properties)
const { name, ...rest } = user;
console.log(rest); // { age: 30, email: '...', address: {...} }
// Function parameters
function greet({ name, age }) {
console.log(`Hello ${name}, you are ${age}`);
}
greet(user); // 'Hello Alice, you are 30'
Array Destructuring
const colors = ['red', 'green', 'blue', 'yellow']; // ❌ Old way const first = colors[0]; const second = colors[1]; // ✅ Destructuring const [first, second] = colors; console.log(first); // 'red' console.log(second); // 'green' // Skip elements const [, , third] = colors; console.log(third); // 'blue' // Rest operator const [primary, ...secondary] = colors; console.log(primary); // 'red' console.log(secondary); // ['green', 'blue', 'yellow'] // Default values const [a, b, c, d, e = 'default'] = colors; console.log(e); // 'default' (array only has 4 items)
Swap Variables
let a = 1; let b = 2; // ❌ Old way (needs temp variable) let temp = a; a = b; b = temp; // ✅ Destructuring swap [a, b] = [b, a]; console.log(a); // 2 console.log(b); // 1 // No temp variable needed!
📡 Real-World: API Responses
// API returns complex object
const response = {
data: {
user: {
id: 123,
profile: {
name: 'Bob',
avatar: 'avatar.jpg'
},
stats: {
followers: 1000,
following: 500
}
}
},
meta: {
status: 200
}
};
// ❌ Old way - Multiple lines
const userId = response.data.user.id;
const userName = response.data.user.profile.name;
const avatar = response.data.user.profile.avatar;
const followers = response.data.user.stats.followers;
// ✅ Destructuring - One line!
const {
data: {
user: {
id: userId,
profile: { name: userName, avatar },
stats: { followers }
}
}
} = response;
console.log(userId, userName, avatar, followers);
// 123, 'Bob', 'avatar.jpg', 1000
React Component Props
// ❌ Old way
function UserCard(props) {
return (
{props.name}
{props.email}
);
}
// ✅ Destructuring in parameters
function UserCard({ name, email, avatar }) {
return (
{name}
{email}
);
}
// With default values
function UserCard({
name,
email,
avatar = 'default-avatar.png',
role = 'user'
}) {
return ...;
}
✅ Common Use Cases
- Function params: Extract only needed properties
- API responses: Pull data from nested JSON
- Import statements: Named imports are destructuring
- React hooks: const [state, setState] = useState()
- Module exports: Extract specific functions
💡 Pro Tips
- Computed property names: const { [key]: value } = obj
- Don’t overdo nesting: Deep destructuring is hard to read
- Use TypeScript: Get autocomplete for destructured properties
- Combine with spread: const newObj = { …user, age: 31 }
🎯 Cheat Sheet
| Pattern | Example |
|---|---|
| Basic object | const { a, b } = obj |
| Rename | const { a: newName } = obj |
| Default value | const { a = 5 } = obj |
| Nested | const { a: { b } } = obj |
| Rest | const { a, ...rest } = obj |
| Array | const [a, b] = arr |
“Refactored React components to use destructuring. 50 lines of ‘const x = props.x’ became 1 line. Code so much cleaner. Should’ve learned this years ago.”
