Object Destructuring

Unpack object properties into variables.

Syntaxconst { 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

Try it yourself
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.

Example · js
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.

Example · js
const { name: username, role: accessLevel = "viewer" } = { name: "Bob" };
console.log(username);    // "Bob"
console.log(accessLevel); // "viewer" – default applied

Destructure function parameters

Destructures an options object in the function signature so each parameter is named and has a default.

Example · js
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

  • Be the first to comment on this lesson.
Object Destructuring — JavaScript | SoundsCode