Back to Home
Objects

How to Destructure Objects

Use destructuring to extract object properties

Quick Answer (2024 ES6+ Way)

javascript
const user = { name: 'Alice', age: 30, city: 'NYC' };
const { name, age } = user;
console.log(name, age); // "Alice" 30

Live Example

javascript
const config = {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  retries: 3
};

const { apiUrl, timeout } = config;
console.log(`API: ${apiUrl}, timeout: ${timeout}`);

Common Variations

With Default Values
javascript
const { name = 'Guest', age = 0 } = user;
console.log(name); // "Guest" if not in user
Rename Variables
javascript
const { name: userName, age: userAge } = user;
Nested Destructuring
javascript
const { address: { city, street } } = user;

❌ Don't Do This (Outdated Way)

Avoid manual property access in loops

javascript
// DON'T DO THIS
var name = user.name;
var age = user.age;

Browser Support

Works in all modern browsers (ES6+)

#destructuring#objects#es6