How to Destructure Object in JavaScript: Simple Guide
In JavaScript, you can extract values from an object using
object destructuring by matching property names inside curly braces. This lets you assign object properties to variables in a concise way, like const { name, age } = person;.Syntax
Object destructuring uses curly braces { } to pick properties from an object and assign them to variables with the same names.
- const: declares variables
{ property1, property2 }: lists properties to extract- = object: the object to destructure
javascript
const { property1, property2 } = object;Example
This example shows how to get name and age from a person object and print them.
javascript
const person = { name: 'Alice', age: 25, city: 'Paris' }; const { name, age } = person; console.log(name); console.log(age);
Output
Alice
25
Common Pitfalls
Common mistakes include:
- Using variable names that don't match object properties (will be
undefined). - Trying to destructure from
nullorundefinedcauses errors. - Not using curly braces for object destructuring.
Always ensure the object exists and property names match.
javascript
const person = { name: 'Bob' }; // Wrong: property 'age' does not exist const { age } = person; console.log(age); // undefined // Right: provide default value const { age = 30 } = person; console.log(age); // 30
Output
undefined
30
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Basic destructuring | Extract properties by name | const { a, b } = obj; |
| Rename variable | Assign property to different variable | const { a: x } = obj; |
| Default values | Use default if property missing | const { a = 10 } = obj; |
| Nested destructuring | Extract nested object properties | const { a: { b } } = obj; |
| Rest properties | Collect remaining properties | const { a, ...rest } = obj; |
Key Takeaways
Use curly braces to extract properties by name from objects.
Variable names must match property names unless renamed explicitly.
Provide default values to avoid undefined when properties are missing.
Avoid destructuring from null or undefined to prevent errors.
You can rename variables and extract nested properties with destructuring.