Destructuring in JavaScript
Problem Statement (Why do we need this?)
In JavaScript, we often work with objects and arrays.
But without a clean way to access values, our code becomes:
repetitive
long
hard to read
Example problem:
const user = {
name: "Amit",
age: 22,
city: "Pune"
};
console.log(user.name);
console.log(user.age);
console.log(user.city);
Here we are repeating user. again and again.
Now imagine doing this in a big project with 50+ fields
This is where destructuring helps us.
What is Destructuring?
Destructuring means extracting values from arrays or objects and storing them in variables in a simple way.
Instead of writing:
user.name
user.age
We directly get:
name
age
1. Array Destructuring
Before (Normal way)
const colors = ["red", "green", "blue"];
const first = colors[0];
const second = colors[1];
const third = colors[2];
Too much repetition
After (Destructuring)
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // red
console.log(second); // green
console.log(third); // blue
Mapping idea:
Array → Variables
[red, green, blue] → first, second, third
2. Object Destructuring
Before
const user = {
name: "Amit",
age: 22
};
const name = user.name;
const age = user.age;
After
const user = {
name: "Amit",
age: 22
};
const { name, age } = user;
console.log(name); // Amit
console.log(age); // 22
Mapping idea:
Object → Variables
{name: "Amit"} → name
Renaming while destructuring
const user = {
name: "Amit"
};
const { name: userName } = user;
console.log(userName); // Amit
Sometimes data is missing.
Without default
const user = {};
const name = user.name;
console.log(name); // undefined
With default
const user = {};
const { name = "Guest" } = user;
console.log(name); // Guest
Array default value
const colors = [];
const [first = "red"] = colors;
console.log(first); // red
Benefits of Destructuring
1. Less code
const { name, age } = user;
Instead of:
const name = user.name;
const age = user.age;
2. More readable
Code becomes clean and easy to understand.
3. Avoid repetition
No need to write user.user.user...