Sub topic 2
Unpacking Objects by Property Name
Array destructuring matches values by position. Object destructuring matches them by name: each variable in the pattern pulls out the property with the same key. This chapter covers how that matching works, what JavaScript actually looks up when you destructure, and the edge cases that come up in real code.
This chapter assumes you can declare variables with let and const, work with plain objects and arrays, write functions and classes, and tell a reference value from a primitive value. Default values, renaming, rest properties, and nested patterns each have their own chapter later. Here they appear only where they explain the basic model.
The basic pattern
An object pattern is a pair of curly braces on the left side of a declaration. Each name inside the braces creates a variable, and that variable gets the value of the property with the same name.
const user = { name: 'Ada', id: 7, active: true };
const { name, id } = user;
console.log(name); // 'Ada'
console.log(id); // 7That declaration does the same thing as two separate property reads:
const user = { name: 'Ada', id: 7, active: true };
const name = user.name;
const id = user.id;
console.log(name, id); // 'Ada' 7The pattern saves you from repeating user. on each line. More importantly, the reader can see in one place which parts of the object the code uses.
Order does not matter
Matching happens by key, so the order of names in the pattern has nothing to do with the order of properties in the object. You can also take only the properties you need.
const user = { name: 'Ada', id: 7, active: true };
const { active, name } = user;
console.log(active); // true
console.log(name); // 'Ada'This is the main practical difference from array destructuring. If a function returns an object, callers can pick any subset of its properties in any order, and adding a new property later does not break them.
Missing properties become undefined
If the object has no property with a given name, the variable is set to undefined. Nothing throws.
const user = { name: 'Ada', id: 7 };
const { email } = user;
console.log(email); // undefinedThis matches what user.email would return. The chapter on default values shows how to supply a fallback in this case.
What destructuring actually reads
Each name in an object pattern is an ordinary property access. That one fact covers several behaviors that surprise people.
Inherited properties and getters
A property access searches the prototype chain, so destructuring finds inherited properties too. Accessor properties (getters) run, and the variable receives what the getter returns.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
get length() {
return Math.hypot(this.x, this.y);
}
}
const p = new Point(3, 4);
const { x, length, toString } = p;
console.log(x); // 3 (own property)
console.log(length); // 5 (getter on Point.prototype)
console.log(typeof toString); // 'function' (from Object.prototype)Built-in objects behave the same way. The properties of a URL are getters on URL.prototype, and destructuring reads them without any problem:
const { hostname, pathname, search } = new URL('https://example.com/docs?q=1');
console.log(hostname); // 'example.com'
console.log(pathname); // '/docs'
console.log(search); // '?q=1'The getter runs once, at the moment of destructuring. The variable holds a snapshot of the value. It is not a live link to the property.
const counter = { count: 1 };
const { count } = counter;
counter.count = 2;
console.log(count); // 1 (the variable kept the value it was given)Methods lose their `this`
Pulling a method out of an object gives you the bare function. When you call it later, it is no longer attached to the object, so this is not the object any more. In strict mode code, which includes modules and class bodies, this becomes undefined.
'use strict';
const counter = {
count: 0,
increment() {
this.count += 1;
return this.count;
},
};
const { increment } = counter;
try {
increment();
} catch (err) {
console.log(err.name); // 'TypeError' (this is undefined)
}
console.log(counter.increment()); // 1 (works when called on the object)Some functions do not use this, and those are safe to destructure. const { max, min } = Math works because Math.max ignores this. For methods that depend on this, call them on the object, or bind them first: const increment = counter.increment.bind(counter).
Primitives are wrapped first
You can destructure strings, numbers, and booleans. JavaScript temporarily wraps the primitive in its wrapper object (String, Number, Boolean), so you can read both own properties and prototype methods.
const { length } = 'hello';
console.log(length); // 5
const { toFixed } = 42;
console.log(typeof toFixed); // 'function'null and undefined have no wrapper objects, so destructuring them throws a TypeError. A later chapter covers that failure in detail and shows how to guard against it.
Computed keys
Sometimes the property name is held in a variable. A pattern can take a computed key in square brackets, but then it must say which variable receives the value, using the key: target form. The chapter on renaming explains that form fully.
const user = { name: 'Ada', id: 7 };
const field = 'id';
const { [field]: value } = user;
console.log(value); // 7This also works for symbol keys, which cannot be written as plain names in a pattern:
const tag = Symbol('tag');
const item = { [tag]: 'featured', title: 'Lamp' };
const { [tag]: itemTag, title } = item;
console.log(itemTag); // 'featured'
console.log(title); // 'Lamp'Where object patterns appear
An object pattern can appear anywhere JavaScript creates a binding: const, let, and var declarations, for...of loops, catch clauses, and function parameters.
const people = [
{ name: 'Ada', age: 36 },
{ name: 'Lin', age: 29 },
];
for (const { name, age } of people) {
console.log(`${name} is ${age}`);
}
// 'Ada is 36'
// 'Lin is 29'
try {
JSON.parse('{bad json');
} catch ({ name, message }) {
console.log(name); // 'SyntaxError'
console.log(typeof message); // 'string'
}In the for...of loop, each pass declares fresh name and age variables. Every iteration gets its own bindings, the same as a plain const loop variable.
The declaration keyword applies to every variable in the pattern. let { a, b } = obj makes both reassignable, and const { a, b } = obj makes neither reassignable. You cannot mix the two in one pattern. Use two declarations if you need both.
Function parameters and destructuring into variables that already exist each have their own chapter. Assigning to existing variables needs extra parentheses, and that chapter explains why.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Misspelling a key, as in `const { nmae } = user` | `nmae` is `undefined`, and nothing throws | Check the key names. A linter or TypeScript catches this |
| Destructuring the same name twice, as in `const { name } = a; const { name } = b;` | `SyntaxError`: identifier already declared | Rename one of them (see the renaming chapter) |
| Destructuring a method that uses `this` | `TypeError` or wrong results when it is called | Call it on the object, or use `.bind` |
| Destructuring `null` or `undefined` | `TypeError` | Guard the value or give the whole pattern a default |
| Expecting the variable to follow later changes | The variable keeps its original value | Read the property again when you need the current value |
The silent misspelling in the first row is the most common of these. Destructuring never checks that a property exists, so a typo looks just like a missing value.
Exercise
Given const config = { mode: 'dev', port: 3000 };, what does const { port, mode, host } = config; console.log(mode, port, host); print, and why does the order of names in the pattern not matter?
Show answer
It prints dev 3000 undefined. Object patterns match by property name, not by position, so port and mode each get the value of the matching key. host is not a property of config, so it is undefined, the same result as config.host.
Exercise
An object is created with const base = { kind: 'shape' }; const circle = Object.create(base); circle.r = 2;. What are kind and r after const { kind, r } = circle;? Would kind appear in a rest property such as const { ...copy } = circle;?
Show answer
kind is 'shape' and r is 2. A named property in a pattern is read with normal property access, which searches the prototype chain, so kind comes from base. A rest property copies only own enumerable properties, so copy is { r: 2 } and does not contain kind.
Exercise
Why does const { toUpperCase } = 'abc'; toUpperCase(); throw a TypeError, while const { max } = Math; max(1, 5); returns 5?
Show answer
String.prototype.toUpperCase uses this to find the string to convert. Called on its own, it has no string as this (it gets undefined), so it throws. Math.max does not use this, so calling it on its own works.