Introduction
If you’ve ever written something like const first = arr[0]; and thought "there's gotta be a cleaner way,” good news, there is, and it’s called destructuring.
What’s Destructuring?
Destructuring is just a fancy term for pulling values out of arrays or objects and sticking them into variables, all in one tidy line of code.
Destructuring Arrays
const [first, second, third] = ['red', 'green', 'blue'];
console.log(first); // red
console.log(second); // green
console.log(third); // blue
Skip Values
const [first, , third] = ['red', 'green', 'blue'];
console.log(first); // red
console.log(third); // blue
Set Defaults
const [x = 10, y = 20] = [];
console.log(x); // 10
console.log(y); // 20
Destructuring Objects
const { name, age } = {
name: "Alice",
age: 25,
country: "USA"
};
console.log(name); // Alice
console.log(age); // 25
Rename While You’re At It
const { name: userName, country: userCountry } = {
name: "Alice",
age: 25,
country: "USA"
};
console.log(userName); // Alice
console.log(userCountry); // USA
Give It a Default
const { city = "Unknown" } = {
name: "Alice",
age: 25,
country: "USA"
};
console.log(city); // Unknown
Destructuring in Function Parameters
function showUser({ name, country }) {
console.log(`${name} is from ${country}`);
}
const person = {
name: "Bob",
country: "France"
};
showUser(person); // Bob is from France
Quick Cheatsheet
// Array
const [a, b] = [1, 2];
// Object
const { x, y } = { x: 10, y: 20 };
// Rename
const { x: renamedX } = { x: 5 };
// Default
const { z = 100 } = {};
Conclusion
Destructuring is one of those features that might look “meh” at first, but once you start using it, you’ll never want to go back.