Sub topic 9
Unpacking Objects with Destructuring
This chapter assumes you can create objects with literals, read properties with dot and bracket notation, and use shorthand and computed keys. It also assumes you know that reading a missing property returns undefined. Destructuring builds directly on those ideas. It is a compact syntax for reading several properties at once and binding them to variables.
The Basic Pattern
An object destructuring pattern looks like an object literal, but it sits on the left side of an assignment. Each name in the pattern reads the property of the same name from the source object.
const user = { id: 7, name: "Lin", email: "[email protected]" };
const { id, name } = user;
console.log(id); // 7
console.log(name); // "Lin"This is equivalent to writing const id = user.id; const name = user.name;. The pattern { id, name } uses the same shorthand as { id, name } in a literal. In a literal, the shorthand builds properties from variables. In a pattern, it builds variables from properties.
A name with no matching property gets undefined. Unlike some languages, JavaScript does not throw an error here:
const { phone } = { id: 7 };
console.log(phone); // undefinedRenaming While Unpacking
Sometimes the property name is not a good variable name, or it clashes with a variable you already have. Use property: variable to read one name and bind another.
const response = { status: 200, "content-type": "text/html" };
const { status: code, "content-type": contentType } = response;
console.log(code); // 200
console.log(contentType); // "text/html"The colon reads opposite to how many people expect. In a literal, { a: b } means "property a holds value b". In a pattern, { a: b } means "take property a and store it in variable b". The left side is always the property and the right side is always the target. Renaming is required for keys like "content-type" that are not valid identifiers.
Computed keys work inside patterns too, but they must be renamed, because the pattern has no identifier to bind on its own:
const field = "email";
const { [field]: value } = { email: "[email protected]" };
console.log(value); // "[email protected]"Default Values
You can supply a default with =. The default applies only when the property's value is exactly undefined. That includes missing properties and properties explicitly set to undefined. It does not apply to null, 0, "", or false.
const settings = { theme: null, fontSize: 0, lang: undefined };
const {
theme = "light",
fontSize = 14,
lang = "en",
timezone = "UTC"
} = settings;
console.log(theme); // null (null is not undefined)
console.log(fontSize); // 0 (0 is not undefined)
console.log(lang); // "en"
console.log(timezone); // "UTC"This matches how default function parameters behave. It is different from the || operator, which would replace 0 and null as well. If your data uses null to mean "not set", destructuring defaults will not help. Use ?? after unpacking instead.
You can combine renaming and defaults. The order is property: variable = default:
const { status: code = 500 } = {};
console.log(code); // 500Defaults Are Evaluated Lazily
A default expression runs only if it is needed. This matters when the default has a cost or a side effect.
function fallback() {
console.log("fallback called");
return 0;
}
const { x = fallback() } = { x: 5 }; // prints nothing
const { y = fallback() } = {}; // prints "fallback called"
console.log(x, y); // 5 0Defaults can also refer to variables bound earlier in the same pattern, because bindings happen left to right:
const { width = 100, height = width / 2 } = { width: 300 };
console.log(height); // 150Nested Patterns
A pattern can contain another pattern to reach into nested objects. The outer key names the property, and the inner pattern unpacks its value.
const order = {
id: 42,
customer: { name: "Ada", address: { city: "London" } }
};
const {
customer: {
name,
address: { city }
}
} = order;
console.log(name); // "Ada"
console.log(city); // "London"Note that customer and address are not bound as variables here. They are only paths. If you want both the nested object and its parts, list the key twice: const { customer, customer: { name } } = order;.
The Nested Missing-Object Error
Nested patterns fail if an intermediate value is undefined or null. This error comes up often:
const order = { id: 42 };
try {
const { customer: { name } } = order;
} catch (err) {
console.log(err instanceof TypeError); // true
}The fix is to give the intermediate level a default empty object:
const order = { id: 42 };
const { customer: { name = "anonymous" } = {} } = order;
console.log(name); // "anonymous"The = {} belongs to customer, and = "anonymous" belongs to name. Note that a default only covers undefined. If customer is null, the default is skipped and destructuring null still throws. For data that may contain null, optional chaining (order.customer?.name) is safer than a nested pattern.
Rest Properties
A rest element, written ...name, collects every remaining property into a new object. It must come last in the pattern and cannot have a trailing comma.
const user = { id: 7, password: "hunter2", name: "Lin", role: "admin" };
const { password, ...publicUser } = user;
console.log(publicUser); // { id: 7, name: "Lin", role: "admin" }This is a common way to omit fields without mutating the original object. Rest has precise rules worth knowing:
| Behavior | Named properties in the pattern | Rest element |
|---|---|---|
| Reads inherited properties | Yes, normal property lookup | No, own properties only |
| Includes non-enumerable properties | Yes, if named | No |
| Includes symbol keys | Yes, if named with a computed key | Yes, if enumerable |
| Creates a new object | No | Yes, a shallow copy |
The rest object is a shallow copy. Nested objects inside it are shared with the source, exactly as with spread syntax { ...obj }:
const source = { a: 1, meta: { tags: ["x"] } };
const { a, ...others } = source;
others.meta.tags.push("y");
console.log(source.meta.tags); // ["x", "y"]The difference between named properties and rest shows up with inherited properties:
const proto = { inherited: "from proto" };
const obj = Object.create(proto);
obj.own = "mine";
const { inherited, ...rest } = obj;
console.log(inherited); // "from proto"
console.log(rest); // { own: "mine" }Destructuring Function Parameters
Destructuring appears most often in function parameters, where it gives you named arguments with defaults.
function connect({ host = "localhost", port = 80, secure = false } = {}) {
return `${secure ? "https" : "http"}://${host}:${port}`;
}
console.log(connect({ port: 8080 })); // "http://localhost:8080"
console.log(connect({ host: "example.com", secure: true })); // "https://example.com:80"
console.log(connect()); // "http://localhost:80"The trailing = {} is important. Without it, calling connect() passes undefined, and destructuring undefined throws a TypeError. With it, the missing argument becomes an empty object and each inner default applies.
Assigning to Existing Variables
Destructuring also works with plain assignment, without const or let. There is a syntax trap here. A statement that begins with { is parsed as a block, not a pattern, so you must wrap the whole assignment in parentheses.
let x, y;
const point = { x: 3, y: 4 };
({ x, y } = point);
console.log(x, y); // 3 4If the previous line has no semicolon, the parenthesis may be read as a function call on that line. Writers who leave out semicolons often put a leading ; before the parenthesis.
Assignment targets can be any valid assignment target, including properties of other objects:
const target = {};
const source = { a: 1, b: 2 };
({ a: target.first, b: target.second } = source);
console.log(target); // { first: 1, second: 2 }Edge Cases
Destructuring calls the same internal property read as dot access. Several behaviors follow from that.
- Primitives are boxed.
const { length } = "hello";gives5, because the string is temporarily wrapped in aStringobject. nullandundefinedthrow.const {} = null;throws aTypeError, even with an empty pattern.- Getters run. If a property is a getter, destructuring calls it, once per mention in the pattern.
- Methods lose
this.const { increment } = counter;extracts the function only. Callingincrement()later runs withthisasundefinedin strict mode, the same problem as assigningcounter.incrementto a variable.
const counter = {
count: 0,
increment() {
return ++this.count;
}
};
const { increment } = counter;
try {
increment(); // module/strict code: this is undefined
} catch (err) {
console.log(err instanceof TypeError); // true
}Common Mistakes
- Reading
{ a: b }as "a is b" instead of "property a goes into variable b". - Expecting defaults to replace
null. - Forgetting
= {}on a destructured parameter or nested level. - Starting an assignment statement with
{and getting a syntax error. - Assuming the rest object is a deep copy.
Exercise
Given const data = { a: 0, b: null, c: { d: undefined } };, what do a, b, d, and e hold after const { a = 1, b = 2, c: { d = 3, e = 4 } } = data;?
Show answer
a is 0 and b is null, because defaults apply only to undefined. d is 3, because its value is explicitly undefined. e is 4, because the property is missing. No variable named c is created.
Exercise
Write a function withoutKeys(obj) that returns a copy of obj without its id and createdAt properties, without mutating obj. Is the result independent of obj?
Show answer
function withoutKeys(obj) { const { id, createdAt, ...rest } = obj; return rest; }. The result is a new object, but the copy is shallow: nested objects are still shared with obj. It also leaves out inherited and non-enumerable properties.
Exercise
Why does function f({ x }) { return x; } throw when called as f(), and how do you fix it?
Show answer
With no argument, the parameter is undefined, and destructuring undefined throws a TypeError. Add a parameter default: function f({ x } = {}) { return x; }, which returns undefined instead of throwing.