Object Destructuring

Object destructuring in JavaScript allows you to extract properties from objects and assign them to variables in a concise syntax.

Illustration of object_destructuring
Illustration of object_destructuring

💡 Basic Syntax

Use curly braces on the left side of the assignment to unpack properties:

const { prop1, prop2 } = object;

This creates variables prop1 and prop2 containing the respective property values from object.

📌 Deep Dive: Extracting Properties

JAVASCRIPT
const user = { name: 'Alice', age: 30 };
const { name, age } = user;
console.log(name); // Alice
console.log(age);  // 30
Output
Alice
30

💡 Renaming Variables

You can assign a property to a variable with a different name:

const { prop: newName } = object;

📌 Deep Dive: Rename During Destructuring

JAVASCRIPT
const user = { name: 'Alice', age: 30 };
const { name: userName, age: userAge } = user;
console.log(userName); // Alice
console.log(userAge);  // 30
Output
Alice
30

💡 Default Values

If a property does not exist in the object, you can assign a default value:

const { prop = defaultValue } = object;

📌 Deep Dive: Using Default Values

JAVASCRIPT
const user = { name: 'Alice' };
const { age = 25 } = user;
console.log(age); // 25
Output
25

⚠️ Important

When destructuring, the variable names must match the property names, unless you rename them explicitly.

💡 Nested Object Destructuring

You can destructure properties from nested objects by matching the nesting pattern:

📌 Deep Dive: Nested Destructuring

JAVASCRIPT
const user = {
  name: 'Alice',
  address: {
    city: 'Wonderland',
    zip: 12345
  }
};
const { address: { city, zip } } = user;
console.log(city); // Wonderland
console.log(zip);  // 12345
Output
Wonderland
12345
Summary of Object Destructuring Syntax
FeatureSyntax Example
Basic Extraction{ prop }
Variable Renaming{ prop: newName }
Default Values{ prop = defaultValue }
Nested Destructuring{ nested: { prop } }