Destructuring in JavaScript
What Is Destructuring?
Destructuring is a shortcut for extracting values from:
Arrays
Objects
and storing them into variables.
Why Destructuring Is Useful
Without destructuring:
const user = {
name: "Ali",
age: 22
};
const name = user.name;
const age = user.age;
With destructuring:
const user = {
name: "Ali",
age: 22
};
const { name, age } = user;
Cleaner and shorter.
Benefits of Destructuring
Destructuring Arrays
Array destructuring extracts values based on position.
Example
const colors = ["red", "blue", "green"]; const [first, second] = colors; console.log(first); console.log(second);
Output
red blue
Array Destructuring Mapping
Skipping Values
const numbers = [10, 20, 30]; const [first, , third] = numbers; console.log(first); console.log(third);
Output
10 30
Destructuring Objects
Object destructuring extracts values using property names.
Example
const user = {
name: "Sara",
city: "Lucknow"
};
const { name, city } = user;
console.log(name);
console.log(city);
Output
Sara Lucknow
Object → Variable Extraction
Renaming Variables
const user = {
name: "Ali"
};
const { name: userName } = user;
console.log(userName);
Output
Ali
Default Values
Used when value may not exist.
Array Default Example
const numbers = [10]; const [a, b = 20] = numbers; console.log(a); console.log(b);
Output
10 20
Object Default Example
const user = {
name: "Ali"
};
const { name, age = 25 } = user;
console.log(age);
Output
25
Before vs After Destructuring
Without Destructuring
const product = {
title: "Laptop",
price: 50000
};
const title = product.title;
const price = product.price;
With Destructuring
const product = {
title: "Laptop",
price: 50000
};
const { title, price } = product;
Destructuring Function Parameters
Very common in modern JavaScript.
Example
function printUser({ name, age }) {
console.log(name);
console.log(age);
}
printUser({
name: "Ali",
age: 22
});
Why This Is Useful
Avoids repetitive access like:
user.name user.age
inside function.
Nested Object Example
const user = {
profile: {
city: "Lucknow"
}
};
const {
profile: { city }
} = user;
console.log(city);
Output
Lucknow
Common Beginner Mistakes
Using Wrong Brackets
Arrays use:
[]
Objects use:
{}
Incorrect Object Destructuring
const [name] = user;
Correct:
const { name } = user;
Practical Examples
Array Example
const fruits = ["apple", "banana"]; const [firstFruit] = fruits; console.log(firstFruit);
Object Example
const student = {
name: "Sara",
course: "Computer Science"
};
const { name, course } = student;
console.log(name);
console.log(course);
Key Takeaways
Final Notes
Destructuring is heavily used in modern JavaScript because it makes code:
Cleaner
Shorter
Easier to maintain
It appears frequently in:
React
APIs
Node.js
Function parameters
Modern frontend frameworks
No attachments.
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!