Destructuring is a powerful feature introduced in ES6 (ECMAScript 2015) that allows you to “unpack” values from arrays or properties from objects into distinct variables. It makes your code cleaner, more readable, and reduces the need for repetitive index-based or dot-notation access.
1. Object Destructuring
Object destructuring uses the variable name to match the key name in the object.
Basic Example
const person = { name: 'Alice', age: 25, city: 'London' };
// Traditional way
// const name = person.name;
// const age = person.age;
// ES6 Destructuring
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 25
Renaming Variables
If you want to use a variable name different from the object key, use a colon :.
const { name: fullName, city: homeTown } = person;
console.log(fullName); // "Alice"
Default Values
You can assign default values in case a property doesn’t exist.
const { country = 'UK' } = person;
console.log(country); // "UK" (since it wasn't in the object)
2. Array Destructuring
Array destructuring is based on the position (index) of the elements.
Basic Example
const colors = ['red', 'green', 'blue'];
// Unpacking by position
const [first, second] = colors;
console.log(first); // "red"
console.log(second); // "green"
Skipping Elements
Use commas to skip over elements you don’t need.
const [primary, , tertiary] = colors;
console.log(primary); // "red"
console.log(tertiary); // "blue"
Using the Rest Operator (...)
You can capture the “rest” of the elements into a new array.
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
3. Advanced Use Cases
Swapping Variables
Destructuring provides a elegant way to swap values without a temporary temp variable.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
Function Parameter Destructuring
This is extremely common in modern frameworks like React. It allows you to pass an object to a function but only extract what you need.
const user = { id: 101, username: 'jsmith', email: 'j@example.com' };
// Destructuring directly in the parameter list
function displayUser({ username, email }) {
console.log(`${username}'s email is ${email}`);
}
displayUser(user); // "jsmith's email is j@example.com"
Nested Destructuring
You can even unpack values from objects nested inside other objects or arrays.
const metadata = {
title: 'My Page',
config: {
theme: 'dark',
version: 1.2
}
};
const { config: { theme } } = metadata;
console.log(theme); // "dark"
