0
0
JavascriptHow-ToBeginner · 3 min read

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 null or undefined causes 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

FeatureDescriptionExample
Basic destructuringExtract properties by nameconst { a, b } = obj;
Rename variableAssign property to different variableconst { a: x } = obj;
Default valuesUse default if property missingconst { a = 10 } = obj;
Nested destructuringExtract nested object propertiesconst { a: { b } } = obj;
Rest propertiesCollect remaining propertiesconst { 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.