JavaScript Destructuring
8 April 2025 | Category: JavaScript
Destructuring is a way to unpack values from arrays or properties from objects into individual variables.
It makes your code shorter, cleaner, and easier to read.
🔹 Array Destructuring
✅ Basic Example:
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
💡 Skip Values:
const [x, , z] = [10, 20, 30];
console.log(x); // 10
console.log(z); // 30
🛑 Default Values:
const [name = "Guest", age = 18] = [];
console.log(name); // "Guest"
console.log(age); // 18
🔹 Object Destructuring
✅ Basic Example:
const person = {
firstName: "John",
lastName: "Doe"
};
const { firstName, lastName } = person;
console.log(firstName); // John
console.log(lastName); // Doe
🧠 Rename Variables:
const { firstName: fName, lastName: lName } = person;
console.log(fName); // John
console.log(lName); // Doe
🛑 Default Values:
const { age = 30 } = person;
console.log(age); // 30 (if age doesn't exist in object)
🧠 Nested Destructuring
🔄 From Object:
const user = {
name: "Alice",
address: {
city: "Paris",
country: "France"
}
};
const { address: { city } } = user;
console.log(city); // Paris
🔄 From Array:
const colors = ["red", ["light green", "dark green"]];
const [mainColor, [lightGreen]] = colors;
console.log(lightGreen); // light green
🔁 Destructuring in Function Parameters
function greet({ name, age }) {
console.log(`Hello ${name}, age ${age}`);
}
const user = { name: "Nora", age: 22 };
greet(user); // Hello Nora, age 22
🔍 Use Cases
- 💬 Cleanly extract props in React
- 📦 Handle API responses
- 🧪 Swap variables
- 🔂 Loop over object/array values
💡 Swapping Variables Using Destructuring
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 5
✅ Summary
Type | Syntax Example |
---|---|
Array | const [a, b] = [1, 2]; |
Object | const {x, y} = obj; |
Rename | const {name: n} = obj; |
Defaults | const [x = 0] = []; |
Nested | const { info: { city } } = user; |
In function | function({ id }) { ... } |