AI Hints
Home›JavaScript Tutorial›Working with Objects
JavaScript · Lesson 62 of 138

Destructuring Objects

Unpacking properties.

⏱ 2 min read▶ Video at 1:15:43🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Just like arrays, objects can be unpacked into variables. But object destructuring matches by name, not by position. It's one of the most common patterns in modern JavaScript.

Destructuring Objects
From the video: Destructuring Objects
  • Unpack objects too
  • Match by name
  • Very common

By name

Curly braces on the left unpack properties with the same names. A colon renames a variable. An equals sign gives a default for a missing property. And it works directly in a function's parameters, which makes functions with options very readable. Run it.

app.jsjavascript
const user = { name: "Ana", age: 29, country: "PT" };

const { name, age } = user;
console.log(name, age);

const { country: code, role = "member" } = user;
console.log(code, role);

function welcome({ name, country = "unknown" }) {
  return `Welcome, ${name} from ${country}!`;
}
console.log(welcome(user));
Output
Ana 29
PT member
Welcome, Ana from PT!

Why it helps

Destructuring in parameters means callers pass one object with named options, in any order. So instead of a function call with five mysterious arguments, you see exactly what each one means. Many libraries and frameworks work this way.

keyvalue
{ a, b } = objby name
{ a: x }rename
{ a = 1 }default
f({ a, b })named options

Nested destructuring

Destructuring can reach into nested objects too. Here we pull the city out of the address, in one line. And the rest syntax, three dots, collects every other property into a new object. That's a neat way to remove a property without changing the original. Run it.

app.jsjavascript
const order = {
  id: 7,
  customer: "Ana",
  address: { city: "Lisbon", zip: "1000" },
};

const { address: { city } } = order;
console.log(city);

const { id, ...details } = order;
console.log(id, Object.keys(details));
Output
Lisbon
7 [ 'customer', 'address' ]

Summary

Object destructuring unpacks properties by name, with renaming and defaults, and works in function parameters. Next, arrays of objects.

Key takeaways
  • const { a } = obj
  • Rename with :
  • Defaults with =
Next up: Arrays of Objects — real data