What is Destructuring?
Destructuring is a way to extract values from arrays or objects and assign them to variables in a clean, readable way.
💡 Key insight
Destructuring makes it easy to extract multiple values from complex data structures with less code.
Array Destructuring
let colors = ["red", "green", "blue"];
// Old way
let first = colors[0];
let second = colors[1];
// Destructuring
let [firstColor, secondColor] = colors;
console.log(firstColor); // "red"
// Skipping elements
let [first, , third] = colors;
console.log(third); // "blue"
Object Destructuring
let person = { name: "Alice", age: 25, city: "New York" };
// Old way
let name = person.name;
let age = person.age;
// Destructuring
let { name, age } = person;
console.log(name); // "Alice"
// Renaming variables
let { name: personName, age: personAge } = person;
Default Values
let person = { name: "Alice" };
let { name, age = 30 } = person;
console.log(age); // 30 (default value)
Nested Destructuring
let user = {
id: 1,
profile: {
name: "Alice",
email: "alice@example.com"
}
};
let { profile: { name, email } } = user;
console.log(name); // "Alice"
Common Mistakes
- Forgetting that variable names in object destructuring must match property names
- Using array destructuring on objects (use object destructuring instead)
- Confusing the order of elements in array destructuring
Quick Quiz
1. What does let [a, b] = [1, 2, 3]; do?
2. What does let { name } = { name: "Alice", age: 25 }; do?
3. How do you rename a variable in object destructuring?
Summary
- Array destructuring:
let [a, b] = array - Object destructuring:
let { name, age } = object - Use
...for the rest operator - Default values:
let { name = "default" } - Nested destructuring:
let { nested: { value } }
