Sub topic 9
Unpacking Objects with Destructuring
This chapter assumes you can read properties with dot and bracket notation and that you know shorthand properties and computed keys from earlier chapters. Destructuring is the same syntax run in reverse. An object literal builds an object from variables. A destructuring pattern pulls variables out of an object.
The Basic Pattern
A destructuring pattern sits on the left of =. Each name in the braces matches a property key, and the value of that property is assigned to a new variable with the same name.
const user = { id: 7, profile: { name: "Lin" } };
const { id, role = "guest", ...rest } = user;
console.log(id); // 7
console.log(role); // "guest"
console.log(rest); // { profile: { name: "Lin" } }This one line does three things:
idreadsuser.id.role = "guest"readsuser.role, which is missing, so the default is used....restcollects every remaining own enumerable property into a new object.
Renaming, Nesting, and Computed Keys
Use key: newName when you want the variable to have a different name than the property. The same colon also lets you go deeper into nested objects.
const order = { id: 42, customer: { name: "Ada", city: "Paris" } };
const field = "id";
const { id: orderId, customer: { name, city = "Unknown" }, [field]: again } = order;
console.log(orderId); // 42
console.log(name); // "Ada"
console.log(city); // "Paris"
console.log(again); // 42In the nested pattern, customer is only a path. It does not become a variable. If you also want customer itself, list it separately: const { customer, customer: { name } } = order;.
When Defaults Apply
A default value is used only when the property's value is undefined. That covers both a missing property and a property that exists with the value undefined. A value of null, 0, or "" is kept as it is.
const { a = 1, b = 1, c = 1 } = { a: undefined, b: null, c: 0 };
console.log(a, b, c); // 1 null 0Destructuring Function Parameters
Destructuring is often used for "options object" parameters. Add = {} after the pattern so that calling the function with no argument still works.
function connect({ host = "localhost", port = 8080 } = {}) {
return `${host}:${port}`;
}
console.log(connect()); // "localhost:8080"
console.log(connect({ port: 3000 })); // "localhost:3000"Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Destructuring `null` or `undefined` | `TypeError: Cannot destructure ...` | Give a default: `= {}`, or check the value first |
| Destructuring a nested object that is missing | `TypeError` on the inner pattern | Add a default for the inner object: `customer: { name } = {}` |
| Assigning to existing variables with `{ a } = obj;` | `SyntaxError`, because the braces are read as a block | Wrap the statement in parentheses: `({ a } = obj);` |
| Expecting `...rest` to be a deep copy | Nested objects are still shared with the original | Use `structuredClone` when you need independence |
| Putting `...rest` before other names | `SyntaxError` | The rest element must come last |
Exercise
Given const cfg = { mode: null, retries: 0 };, what do mode and retries hold after const { mode = "dev", retries = 3, timeout = 1000 } = cfg;?
Show answer
mode is null and retries is 0, because defaults apply only when the value is undefined. timeout is 1000, because the property is missing.
Exercise
Write one statement that takes const res = { data: { items: [1, 2] }, status: 200 }; and creates a variable list holding the items array and a variable code holding the status.
Show answer
const { data: { items: list }, status: code } = res;