How does destructuring work in JavaScript?
Destructuring unpacks values from arrays or properties from objects into distinct variables in a single expression.
JavaScript
Overview
Destructuring assignment is a syntax that makes it easy to unpack values from arrays or properties from objects into individual variables. It is one of the most-used ES2015 features - you see it everywhere in React, Node.js, and modern JS.
Key Points
- •Array destructuring uses `[]`: values are matched by position.
- •Object destructuring uses `{}`: values are matched by key name.
- •You can rename while destructuring: `const { name: userName } = user`.
- •Default values fill in when a value is `undefined`: `const { role = "user" } = obj`.
- •Rest element collects remaining values: `const [first, ...rest] = arr`.
- •Destructuring works in function parameters - very common in React components.
Examples
Array destructuring
javascriptconst [red, green, blue] = [255, 128, 0];
console.log(red); // 255
console.log(green); // 128
// Skip elements with empty slots
const [,, third] = [1, 2, 3];
console.log(third); // 3
// Swap variables in one line
let a = 1, b = 2;
[a, b] = [b, a]; // a = 2, b = 1Object destructuring with rename and default
javascriptconst user = { name: 'Alice', age: 30 };
const { name, age } = user;
console.log(name); // 'Alice'
// Rename
const { name: userName } = user;
console.log(userName); // 'Alice'
// Default value
const { role = 'guest' } = user;
console.log(role); // 'guest' (key doesn't exist in user)Nested destructuring
javascriptconst { address: { city, zip } } = {
name: 'Bob',
address: { city: 'Austin', zip: '78701' },
};
console.log(city); // 'Austin'Destructuring in function parameters (common in React)
javascript// Without destructuring
function greet(props) {
return `Hello, ${props.name}!`;
}
// With destructuring
function greet({ name, greeting = 'Hello' }) {
return `${greeting}, ${name}!`;
}
greet({ name: 'Alice' }); // 'Hello, Alice!'
greet({ name: 'Bob', greeting: 'Hi' }); // 'Hi, Bob!'Pro Tip
Object destructuring in function parameters is the idiomatic way to handle options/config objects in JavaScript. It makes the accepted keys self-documenting and lets you set defaults inline without extra code inside the function body.