Object destructuring pulls properties out of an object into variables with matching names.
const user = { name: "Maya", age: 28, city: "Pune" };
const { name, age } = user;
console.log(name, age); // → Maya 28
It is a shorter way to write const name = user.name; const age = user.age;.
Renaming
Use key: newName when you want a different variable name.
const user = { name: "Maya", age: 28 };
const { name: userName, age: years } = user;
console.log(userName, years); // → Maya 28
Default values
If a property is missing (undefined), the default is used.
const settings = { theme: "dark" };
const { theme, fontSize = 16 } = settings;
console.log(theme, fontSize); // → dark 16
Nested objects
const post = { title: "Hello", author: { name: "Deepak", id: 1 } };
const { title, author: { name: authorName } } = post;
console.log(title, authorName); // → Hello Deepak
Rest
Collect the remaining properties into a new object.
const { id, ...details } = { id: 7, name: "Notebook", price: 4 };
console.log(id); // → 7
console.log(details); // → { name: Notebook, price: 4 }
In function parameters
This is where destructuring is most useful. The function documents which properties it needs, and you can give defaults.
function showUser({ name, age = 18, admin = false }) {
return `${name} (${age})${admin ? " [admin]" : ""}`;
}
console.log(showUser({ name: "Maya", age: 28 })); // → Maya (28)
console.log(showUser({ name: "Sam", admin: true })); // → Sam (18) [admin]
Destructuring in loops and callbacks
const products = [{ name: "Pen", price: 2 }, { name: "Book", price: 12 }];
for (const { name, price } of products) {
console.log(name, price);
}
console.log(products.map(({ name }) => name)); // → ["Pen", "Book"]
A syntax gotcha
When destructuring into existing variables, wrap the statement in parentheses, otherwise the braces look like a block.
let a, b;
({ a, b } = { a: 1, b: 2 });
console.log(a, b); // → 1 2