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

💡 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
const user = { name: 'Alice', age: 30 };
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 30
30
💡 Renaming Variables
You can assign a property to a variable with a different name:
const { prop: newName } = object;
📌 Deep Dive: Rename During Destructuring
const user = { name: 'Alice', age: 30 };
const { name: userName, age: userAge } = user;
console.log(userName); // Alice
console.log(userAge); // 30
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
const user = { name: 'Alice' };
const { age = 25 } = user;
console.log(age); // 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
const user = {
name: 'Alice',
address: {
city: 'Wonderland',
zip: 12345
}
};
const { address: { city, zip } } = user;
console.log(city); // Wonderland
console.log(zip); // 12345
12345
| Feature | Syntax Example |
|---|---|
| Basic Extraction | { prop } |
| Variable Renaming | { prop: newName } |
| Default Values | { prop = defaultValue } |
| Nested Destructuring | { nested: { prop } } |
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What is the correct syntax to extract the property color from car object using destructuring?
Question 2 of 2
How do you assign the property age from person to a variable named years using object destructuring?
Loading results...