How to Use Destructuring in JavaScript
Learn how to extract values from arrays and objects using destructuring assignment in JavaScript.
Destructuring lets you unpack values from arrays or properties from objects into distinct variables, making your code cleaner and more readable.
Array Destructuring
Basic Syntax
const colors = ['red', 'green', 'blue'];
// Without destructuring
const first = colors[0];
const second = colors[1];
// With destructuring
const [red, green, blue] = colors;
console.log(red); // 'red'
console.log(green); // 'green'
console.log(blue); // 'blue'
Skipping Elements
const numbers = [1, 2, 3, 4, 5];
// Skip elements with empty slots
const [first, , third] = numbers;
console.log(first); // 1
console.log(third); // 3
// Get first and last
const [head, ...rest] = numbers;
console.log(head); // 1
console.log(rest); // [2, 3, 4, 5]
Default Values
const colors = ['red'];
const [primary, secondary = 'blue'] = colors;
console.log(primary); // 'red'
console.log(secondary); // 'blue' (default value)
Swapping Variables
let a = 1;
let b = 2;
// Swap without temp variable
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
Object Destructuring
Basic Syntax
const person = {
name: 'Alice',
age: 30,
city: 'New York'
};
// Without destructuring
const name = person.name;
const age = person.age;
// With destructuring
const { name, age, city } = person;
console.log(name); // 'Alice'
console.log(age); // 30
Renaming Variables
const person = { name: 'Alice', age: 30 };
// Rename while destructuring
const { name: personName, age: personAge } = person;
console.log(personName); // 'Alice'
console.log(personAge); // 30
Default Values
const person = { name: 'Alice' };
const { name, age = 25, city = 'Unknown' } = person;
console.log(name); // 'Alice'
console.log(age); // 25 (default)
console.log(city); // 'Unknown' (default)
Nested Destructuring
const user = {
name: 'Alice',
address: {
city: 'New York',
country: 'USA'
}
};
// Nested object destructuring
const { name, address: { city, country } } = user;
console.log(name); // 'Alice'
console.log(city); // 'New York'
console.log(country); // 'USA'
Function Parameters
Destructuring in Parameters
// Object parameter destructuring
function greet({ name, age }) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
greet({ name: 'Alice', age: 30 });
// With defaults
function createUser({ name, role = 'user', active = true } = {}) {
return { name, role, active };
}
console.log(createUser({ name: 'Bob' }));
// { name: 'Bob', role: 'user', active: true }
Array Parameter Destructuring
// Array parameter destructuring
function getCoordinates([x, y]) {
console.log(`X: ${x}, Y: ${y}`);
}
getCoordinates([10, 20]);
// Return multiple values
function minMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const [min, max] = minMax([3, 1, 4, 1, 5]);
console.log(min, max); // 1 5
Practical Examples
API Response Handling
const response = {
status: 200,
data: {
user: { id: 1, name: 'Alice' },
posts: [{ title: 'Post 1' }, { title: 'Post 2' }]
}
};
const {
status,
data: { user: { name }, posts }
} = response;
console.log(status); // 200
console.log(name); // 'Alice'
console.log(posts); // [{ title: 'Post 1' }, { title: 'Post 2' }]
React Props
// Common in React components
function UserCard({ name, email, avatar = '/default.png' }) {
return `<div>${name} - ${email}</div>`;
}
// Array destructuring with useState
const [count, setCount] = useState(0);
Loop Destructuring
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
];
// Destructure in for...of
for (const { name, age } of users) {
console.log(`${name} is ${age}`);
}
// Destructure in map
const names = users.map(({ name }) => name);
console.log(names); // ['Alice', 'Bob']
Rest with Destructuring
const person = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
phone: '123-456-7890'
};
// Extract some, keep the rest
const { name, ...contactInfo } = person;
console.log(name); // 'Alice'
console.log(contactInfo); // { age: 30, email: '...', phone: '...' }
Summary
- Array destructuring:
const [a, b] = array - Object destructuring:
const { prop } = object - Rename:
const { prop: newName } = object - Defaults:
const { prop = default } = object - Nested:
const { outer: { inner } } = object - Rest:
const { a, ...rest } = object - Use in function parameters for cleaner APIs