Object destructuring is a modern JavaScript feature that makes it easy to extract values from objects into separate variables. It keeps our code clean, short, and simple to read.
Let’s walk through the concept step by step.
⭐ What Is Object Destructuring?
Suppose we have an object like this:
const person = {
name: "Heartin",
age: 16,
country: "Canada"
};
Without destructuring, we retrieve values like this:
console.log(person.name);
console.log(person.age);
With object destructuring, we can directly pull values into variables:
const { name, age } = person;
console.log(name);
console.log(age);
This means:
“Take the
nameandageproperties from the objectpersonand create variables with those names.”
⭐ Why Use Object Destructuring?
It helps you:
- avoid repeating
object.property - make functions cleaner
- handle missing values gracefully
- extract multiple properties in one go
- write modern, readable code
Today, destructuring is widely used in JavaScript projects of all types.
⭐ Basic Syntax
✔ Basic example
const { name, age } = person;
⭐ Renaming Variables
You can rename the extracted variables:
const { name: fullName, age: years } = person;
console.log(fullName);
console.log(years);
⭐ Adding Default Values
If a property doesn’t exist, you can give it a fallback:
const { city = "Unknown" } = person;
console.log(city); // "Unknown"
⭐ Nested Object Destructuring
Works even for deep objects:
const user = {
info: {
username: "heartin",
email: "example@gmail.com"
}
};
const { info: { username, email } } = user;
console.log(username);
console.log(email);
⭐ Destructuring in Function Parameters
You can destructure right inside the function parameter list.
Without destructuring:
function showInfo(person) {
console.log(person.name, person.age);
}
With destructuring:
function showInfo({ name, age }) {
console.log(name, age);
}
This keeps function signatures concise.
⭐ Does This Work in TypeScript?
Absolutely.
TypeScript supports destructuring, with the addition of types.
type Person = {
name: string;
age: number;
};
function showInfo({ name, age }: Person) {
console.log(name, age);
}
Same syntax — with type safety.
⭐ Quick Summary
| Feature | Description |
|---|---|
| Extract values from objects | ✔ Done using {} |
| Rename variables | ✔ Supported |
| Default values | ✔ Supported |
| Nested destructuring | ✔ Supported |
| Function parameter destructuring | ✔ Supported |
| Works in TypeScript | ✔ Yes |
Object destructuring is a core JavaScript tool used in modern coding for cleaner and more expressive programs.