2.5 Destructuring Assignment
What is Destructuring?
Destructuring Assignment is an ES6 syntax that extracts values from arrays or objects into individual variables. It makes code much more concise and readable.
// Old way
const arr = [1, 2, 3];
const first = arr[0];
const second = arr[1];
// Destructuring
const [a, b, c] = [1, 2, 3];
Array Destructuring
Basic Usage
const colors = ["red", "green", "blue"];
const [red, green, blue] = colors;
console.log(red); // "red"
console.log(green); // "green"
console.log(blue); // "blue"
// Skipping elements
const [, , third] = colors;
console.log(third); // "blue"
const [r, , b] = colors;
console.log(r, b); // "red" "blue"
Default Values
const [a = 1, b = 2, c = 3] = [10, 20];
console.log(a); // 10 (assigned value)
console.log(b); // 20 (assigned value)
console.log(c); // 3 (default — was undefined)
Rest Pattern
const numbers = [1, 2, 3, 4, 5];
const [head, ...tail] = numbers;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
Variable Swap
let x = 1;
let y = 2;
// Old way (temp variable needed)
let temp = x;
x = y;
y = temp;
// Destructuring (elegant!)
[x, y] = [y, x];
console.log(x, y); // 2 1
Object Destructuring
Basic Usage
const user = {
name: "Alice",
age: 25,
email: "alice@example.com",
};
const { name, age, email } = user;
console.log(name); // "Alice"
console.log(age); // 25
console.log(email); // "alice@example.com"
Renaming Variables
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"
console.log(userAge); // 25
// Variables name, age are NOT created
// Useful in API responses
const { data: responseData, status: statusCode } = await fetch('/api/user');
Default Values
const config = { theme: "dark" };
const {
theme = "light",
language = "en",
fontSize = 14,
} = config;
console.log(theme); // "dark" (from config)
console.log(language); // "en" (default)
console.log(fontSize); // 14 (default)
Rest Pattern
const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a); // 1
console.log(b); // 2
console.log(others); // { c: 3, d: 4 }
// Remove sensitive fields
const { password, ...safeUser } = userWithPassword;
// safeUser has no password
Nested Object Destructuring
const person = {
name: "Alice",
address: {
city: "New York",
zip: "10001",
},
contact: {
email: "alice@example.com",
},
};
const {
name,
address: { city, zip },
contact: { email },
} = person;
console.log(name); // "Alice"
console.log(city); // "New York"
console.log(email); // "alice@example.com"
// address, contact variables NOT created
Function Parameter Destructuring
// Without destructuring
function createUser(options) {
const name = options.name;
const age = options.age || 0;
}
// With destructuring
function createUser({ name, age = 0, role = "user" }) {
console.log(`${name} (${age}) - ${role}`);
}
createUser({ name: "Alice", age: 25 });
// "Alice (25) - user"
// Common React pattern
function Button({ label, onClick, disabled = false, className = "" }) {
return `<button class="${className}">${label}</button>`;
}
Destructuring in for...of
const users = [
{ id: 1, name: "Alice", role: "admin" },
{ id: 2, name: "Bob", role: "user" },
];
for (const { id, name, role } of users) {
console.log(`${id}: ${name} (${role})`);
}
// Map iteration
const map = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Object.entries iteration
const obj = { x: 10, y: 20, z: 30 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} = ${value}`);
}
Pro Tips
Destructuring Function Return Values
// Return multiple values (array)
function minMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = minMax([3, 1, 4, 1, 5, 9]);
console.log(min, max); // 1 9
// Return multiple values (object) — accessible by name
function parseDate(dateStr) {
const [year, month, day] = dateStr.split('-').map(Number);
return { year, month, day };
}
const { year, month, day } = parseDate("2024-03-15");
console.log(year, month, day); // 2024 3 15
Dynamic Key Destructuring
const key = "name";
const { [key]: value } = { name: "Alice" };
console.log(value); // "Alice"
// Environment variable handling
function getEnvVar(varName, defaultValue = "") {
const { [varName]: value = defaultValue } = process.env;
return value;
}
const port = getEnvVar("PORT", "3000");