JavaScript Destructuring (Arrays & Objects) Explained
Destructuring is a powerful ES6 feature that lets you extract values from arrays or properties from objects into separate variables in a cleaner and more readable way.
1. Array Destructuring
Use square brackets [] to extract values from an array.
Example:
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // red
console.log(second); // green
console.log(third); // blue
Skip Elements in Array
const [first, , third] = colors;
console.log(third); // blue
Default Values in Array
const [x, y, z = "black"] = ["white", "gray"];
console.log(z); // black
2. Object Destructuring
Use curly braces {} to extract properties from an object.
Example:
const user = {
name: "Alice",
age: 28,
country: "USA"
};
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 28
Rename Variables in Object Destructuring
const { country: location } = user;
console.log(location); // USA
Default Values in Object
const { city = "New York" } = user;
console.log(city); // New York
3. Nested Destructuring
Array Inside Object:
const product = {
name: "Laptop",
specs: ["Intel", "16GB", "512GB SSD"]
};
const { specs: [cpu, ram] } = product;
console.log(cpu); // Intel
console.log(ram); // 16GB
Object Inside Object:
const employee = {
id: 101,
contact: {
email: "john@example.com"
}
};
const { contact: { email } } = employee;
console.log(email); // john@example.com
✅ 4. Destructuring in Function Parameters
Destructure values directly in the function argument.
Object Parameters:
function greet({ name, age }) {
console.log(`Hi ${name}, age ${age}`);
}
greet({ name: "Mia", age: 30 }); // Hi Mia, age 30
Array Parameters:
function showColors([c1, c2]) {
console.log(c1, c2);
}
showColors(["pink", "purple"]); // pink purple
Destructuring: When to Use It?
- Clean up your code
- Reduce repetition
- Extract multiple values in one line
- Use in React/Node APIs, loops, function returns