Object Destructuring
Unpack object properties into variables.
Syntax
const { name, age } = person;Destructuring pulls properties out of an object into variables that share the property names.
Renaming and defaults
- Rename with
{ name: fullName }. - Provide a default with
{ role = 'user' }.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Unpack name and email from a user object returned by an API without referencing user.name and user.email repeatedly.
- Extract only the needed fields from a large config object at the top of a module.
- Destructure function parameters to accept an options object while naming each option clearly.
More examples
Object destructuring
Extracts name and email from a user object into standalone variables, ignoring other properties.
const user = { id: 1, name: "Alice", email: "[email protected]", role: "admin" };
const { name, email } = user;
console.log(name, email);Rename during destructuring
Renames destructured properties with a colon and supplies a default value when the property is absent.
const { name: username, role: accessLevel = "viewer" } = { name: "Bob" };
console.log(username); // "Bob"
console.log(accessLevel); // "viewer" – default appliedDestructure function parameters
Destructures an options object in the function signature so each parameter is named and has a default.
function createPost({ title, body, draft = false }) {
return { title, body, draft, createdAt: new Date().toISOString() };
}
const post = createPost({ title: "Hello", body: "World" });
console.log(post.draft); // false
Discussion