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
JavaScript
const [first, second, third] = ['red', 'green', 'blue'];
console.log(first); // red
console.log(second); // green
console.log(third); // blueSkip Values
JavaScript
const [first, , third] = ['red', 'green', 'blue'];
console.log(first); // red
console.log(third); // blueSet Defaults
JavaScript
const [x = 10, y = 20] = [];
console.log(x); // 10
console.log(y); // 20Destructuring Objects
JavaScript
const { name, age } = {
name: "Alice",
age: 25,
country: "USA"
};
console.log(name); // Alice
console.log(age); // 25Rename While You’re At It
JavaScript
const { name: userName, country: userCountry } = {
name: "Alice",
age: 25,
country: "USA"
};
console.log(userName); // Alice
console.log(userCountry); // USAGive It a Default
JavaScript
const { city = "Unknown" } = {
name: "Alice",
age: 25,
country: "USA"
};
console.log(city); // UnknownDestructuring in Function Parameters
JavaScript
function showUser({ name, country }) {
console.log(`${name} is from ${country}`);
}
const person = {
name: "Bob",
country: "France"
};
showUser(person); // Bob is from FranceQuick Cheatsheet
JavaScript
// 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.


Join the conversation! Your thoughts help the community grow.