Sub topic 10
Reaching into Nested Structures
This chapter assumes you already know the basics of array and object destructuring, default values in patterns, and renaming with property: newName. Those topics were covered in earlier chapters. Here the patterns are nested: one pattern sits inside another so it can follow the shape of the data down several levels.
Real data is rarely flat. API responses, configuration files, and application state usually hold objects inside objects and arrays inside objects. Nested destructuring lets one declaration pull out the leaf values you need, with no chain of intermediate variables.
The Working Model: Patterns Mirror the Data
A destructuring pattern describes a shape. Inside an object pattern, the part after the colon can be another pattern instead of a variable name. The same holds for each position in an array pattern. JavaScript reads the outer value, finds the property or element, and destructures that value again with the inner pattern.
const order = {
id: 1,
customer: { name: 'Lin', address: { city: 'Oslo', zip: '0150' } },
items: [
{ sku: 'A1', qty: 2 },
{ sku: 'B7', qty: 1 },
],
};
const {
id,
customer: {
name,
address: { city },
},
items: [{ sku: firstSku }, { qty: secondQty }],
} = order;
console.log(id); // 1
console.log(name); // 'Lin'
console.log(city); // 'Oslo'
console.log(firstSku); // 'A1'
console.log(secondQty); // 1Object patterns and array patterns can be mixed in any order. items: [...] matches the items property by name, and then matches its elements by position. { sku: firstSku } then matches the first element by property name and renames it.
Only the leaves become variables
This rule causes the most confusion. In customer: { name }, the word customer is a property key that tells JavaScript where to look. It does not create a variable. After the declaration above, name exists and customer does not.
const order = { customer: { name: 'Lin' } };
const { customer: { name } } = order;
console.log(name); // 'Lin'
try {
console.log(customer);
} catch (err) {
console.log(err instanceof ReferenceError); // true
}If you want both the parent object and something inside it, list the property twice. A pattern can mention the same property more than once:
const order = { customer: { name: 'Lin', tier: 'gold' } };
const { customer, customer: { tier } } = order;
console.log(customer); // { name: 'Lin', tier: 'gold' }
console.log(tier); // 'gold'The Common Error: A Missing Intermediate Object
A missing leaf is harmless. You get undefined, the same as with flat destructuring. A missing intermediate object is a different case. JavaScript has to destructure undefined using the inner pattern, and that throws a TypeError.
const order = { id: 1, customer: { name: 'Lin' } };
const { customer: { email } } = order;
console.log(email); // undefined (missing leaf: fine)
try {
const { shipping: { city } } = order; // shipping is undefined
} catch (err) {
console.log(err instanceof TypeError); // true
}The fix is to give the intermediate level a default. When shipping is undefined, the default {} is used, and destructuring {} simply yields undefined for city:
const order = { id: 1, customer: { name: 'Lin' } };
const { customer: { name }, shipping: { city } = {} } = order;
console.log(name); // 'Lin'
console.log(city); // undefined (no TypeError, thanks to the = {} default)For an intermediate array, use = [] in the same way:
const post = { title: 'Hello' };
const { tags: [firstTag] = [] } = post;
console.log(firstTag); // undefinedDefaults at several levels
The intermediate default and the leaf defaults are independent, and you will often want both. The outer = {} stops the crash. The inner defaults supply real fallback values.
function readSettings(config) {
const { settings: { theme = 'light', fontSize = 14 } = {} } = config;
return `${theme}/${fontSize}`;
}
console.log(readSettings({})); // 'light/14'
console.log(readSettings({ settings: {} })); // 'light/14'
console.log(readSettings({ settings: { theme: 'dark' } })); // 'dark/14'
console.log(readSettings({ settings: { fontSize: 18 } })); // 'light/18'The position of each default matters. settings: { theme = 'light' } = {} reads like this: "take settings, use {} if it is undefined, then take theme from it, using 'light' if that is undefined."
Defaults are evaluated lazily
A default expression runs only when it is needed. That makes a function call safe to use as a default, even an expensive one:
function fallbackAddress() {
console.log('fallback called');
return { city: 'Unknown' };
}
const { address: { city } = fallbackAddress() } = { address: { city: 'Oslo' } };
console.log(city); // 'Oslo' ("fallback called" is never printed)
const { address: { city: city2 } = fallbackAddress() } = {};
// prints "fallback called"
console.log(city2); // 'Unknown'Nested Patterns in Parameters and Loops
Nested patterns work anywhere a pattern is allowed, including function parameters and for...of heads. The defensive defaults matter even more in parameters, because callers may leave out arguments altogether.
function describe({
user: { name = 'anonymous', roles: [primaryRole = 'viewer'] = [] } = {},
} = {}) {
return `${name} (${primaryRole})`;
}
console.log(describe()); // 'anonymous (viewer)'
console.log(describe({ user: { name: 'Bo' } })); // 'Bo (viewer)'
console.log(describe({ user: { name: 'Ada', roles: ['admin', 'editor'] } })); // 'Ada (admin)'There are four defaults here, and each guards one level: the whole argument, user, roles, and the first role. Leave one out and some call will crash or return undefined.
In loops, nested destructuring keeps the loop body short:
const rows = [
{ id: 1, meta: { tags: ['new', 'sale'] } },
{ id: 2, meta: { tags: [] } },
];
for (const { id, meta: { tags: [firstTag = 'none'] } } of rows) {
console.log(id, firstTag);
}
// 1 'new'
// 2 'none'Object.entries returns an array of [key, value] pairs. Nested array patterns unpack it neatly, and they can reach further into the values:
const inventory = { apples: { count: 3 }, pears: { count: 0 } };
for (const [fruit, { count }] of Object.entries(inventory)) {
console.log(`${fruit}: ${count}`);
}
// apples: 3
// pears: 0Deciding How Deep to Go
Being able to destructure five levels deep does not mean you should. A deep pattern ties your code tightly to the data's shape, and it gets harder to read with every level. Optional chaining (?.) is often the clearer choice for a single deep value, and it also handles null.
const order = { id: 1, shipping: null };
const city = order.shipping?.city ?? 'Unknown';
console.log(city); // 'Unknown'| Situation | Better choice | Reason |
|---|---|---|
| Several values from the same subtree | Nested destructuring | One declaration names every value you use |
| One value far down the tree | Optional chaining | Shorter, and the path reads left to right |
| Intermediate may be `null` | Optional chaining with `??` | Destructuring defaults ignore `null` |
| Function options with nested groups | Nested parameter destructuring with `= {}` at each level | Documents the expected shape in the signature |
| Pattern deeper than about three levels | Split into two declarations | Easier to read and to change |
Splitting a deep pattern into steps is a valid choice and often the more readable one:
const response = { data: { user: { profile: { email: '[email protected]', verified: true } } } };
const { data: { user } = {} } = response;
const { profile: { email, verified = false } = {} } = user ?? {};
console.log(email, verified); // '[email protected]' trueSummary
- A nested pattern follows the shape of the data. Object patterns match by name, array patterns match by position, and the two can be mixed freely.
- Only the leaf names become variables. To keep an intermediate object too, list its property a second time.
- A missing leaf gives
undefined. A missing intermediate throws aTypeErrorunless you give it a default such as= {}or= []. - Defaults at different levels are independent and are evaluated lazily.
- For one deep value, or for data that may contain
null, optional chaining is usually clearer.
Exercise
After running const { meta: { author: { name } } } = { meta: { author: { name: 'Kim' } } };, which variables exist: meta, author, name, or all three? What happens if you then run console.log(author)?
Show answer
Only name exists, and its value is 'Kim'. meta and author are property keys that guide the pattern and are not bindings. console.log(author) throws a ReferenceError, unless a variable named author was declared somewhere else in scope.
Exercise
Write one declaration that reads city from data.shipping.address.city and falls back to 'Unknown'. It must not throw when shipping, address, or city is missing (absent, not null).
Show answer
const { shipping: { address: { city = 'Unknown' } = {} } = {} } = data; The = {} after address guards against a missing address. The = {} after the shipping pattern guards against a missing shipping. = 'Unknown' supplies the leaf value.
Exercise
Given const res = { body: null };, does const { body: { items = [] } = {} } = res; throw? Explain why, and give a version that does not throw.
Show answer
Yes, it throws a TypeError. Destructuring defaults apply only when the value is undefined, so body stays null and JavaScript tries to destructure null. One safe version is const { items = [] } = res.body ?? {};, because ?? replaces both null and undefined with {} before destructuring.