JavaScript Destructuring
Destructuring is a compact syntax for unpacking values from arrays, or properties from objects, into separate variables. It turns three or four lines of "take this, take that" into one readable line, and it's everywhere in modern JavaScript code.
Object destructuring
Put the property names you want inside { } on the left of the =. Each becomes a variable with the property's value:
const user = { name: "Mara", age: 34, city: "Porto", role: "admin" };
// without destructuring
const name1 = user.name;
const age1 = user.age;
// with destructuring
const { name, age, city } = user;
console.log(name, age, city);
console.log(name1 === name, age1 === age);Mara 34 Porto
true true
The order inside the braces doesn't matter — names are matched to properties. Missing properties give undefined.
Renaming and defaults
Use property: newName to pick a different variable name, and = value to set a default for missing (or undefined) properties:
const settings = { theme: "dark", size: undefined };
const { theme: colorScheme, size = 14, language = "en" } = settings;
console.log(colorScheme, size, language);dark 14 en
Nested objects and the rest
You can reach into nested objects, and collect the remaining properties with ...rest:
const order = {
id: 501,
customer: { name: "Kai", address: { city: "Berlin", zip: "10115" } },
total: 89.5,
paid: true,
};
const {
id,
customer: { name, address: { city } },
...summary
} = order;
console.log(id, name, city);
console.log(summary);501 Kai Berlin
{ total: 89.5, paid: true }
Array destructuring
For arrays, use [ ] and the values are taken by position. Skip positions with an empty slot, and gather the rest with ...:
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;
console.log(red, green, blue);
const [first, , third] = ["a", "b", "c", "d"];
console.log(first, third);
const [winner, ...others] = ["Ana", "Ben", "Cy", "Dee"];
console.log(winner, others);
const [x = 0, y = 0] = [5];
console.log(x, y);
let p = 1, q = 2;
[p, q] = [q, p]; // swap without a temp variable
console.log(p, q);255 128 0
a c
Ana [ 'Ben', 'Cy', 'Dee' ]
5 0
2 1
Destructuring function parameters
This is where destructuring really shines. A function can accept an options object and unpack it right in its parameter list, with defaults — callers then pass arguments by name, in any order:
function createButton({ label, color = "blue", size = "medium", disabled = false } = {}) {
return `<button class="${color} ${size}"${disabled ? " disabled" : ""}>${label}</button>`;
}
console.log(createButton({ label: "Save" }));
console.log(createButton({ label: "Delete", color: "red", disabled: true }));<button class="blue medium">Save</button>
<button class="red medium" disabled>Delete</button>
The = {} at the end lets you call createButton() with no argument at all without an error.
In loops
Destructuring combines nicely with for…of over Object.entries(), Maps, and arrays of objects:
const inventory = [
{ item: "laptop", qty: 4 },
{ item: "mouse", qty: 25 },
];
for (const { item, qty } of inventory) {
console.log(`${item}: ${qty}`);
}
const capitals = { Spain: "Madrid", Kenya: "Nairobi" };
for (const [country, capital] of Object.entries(capitals)) {
console.log(`${capital} is the capital of ${country}`);
}laptop: 4
mouse: 25
Madrid is the capital of Spain
Nairobi is the capital of Kenya
Note: Destructuring
nullorundefinedthrows aTypeError("Cannot destructure…"). Defaults like= {}in parameters protect against that.
Test yourself
After const { a, c } = { a: 1, b: 2, c: 3 };, what is c?
- 2
- 3
- undefined
- An error
After const [, second] = [10, 20, 30];, what is second?
- 10
- 20
- 30
- undefined
What does const { title: heading } = { title: "Hi" }; create?
- A variable named title
- A variable named heading with value "Hi"
- Both title and heading
- An object