Default Values in Nested Destructuring
You'll learn how to safely handle missing properties or array elements at any level of destructuring, preventing undefined values from breaking your code.
When destructuring nested structures, you might encounter missing properties or array elements at any depth. Just like you learned to provide default values in basic destructuring, you can apply the same safety net at every nesting level.
The Core Idea
Imagine opening a box that's supposed to contain another box, which contains a gift. What if one of the boxes is empty? Default values at each level ensure you always have something to work with, no matter where the structure is incomplete.
Syntax
You assign defaults using the = operator at any level of the destructuring pattern:
// Nested objects with defaults
const user = {
profile: {
// name is missing
age: 25
}
};
const { profile: { name = 'Anonymous', age = 0 } } = user;
console.log(name); // 'Anonymous' (default)
console.log(age); // 25 (from object)
// Nested arrays with defaults
const coords = [[10]]; // second element missing
const [[x = 0, y = 0]] = coords;
console.log(x); // 10 (from array)
console.log(y); // 0 (default)
// Mixed nesting with defaults at multiple levels
const data = {
location: {} // city is missing, coordinates is missing
};
const {
location: {
city = 'Unknown',
coordinates: [lat = 0, lng = 0] = []
} = {}
} = data;
console.log(city); // 'Unknown'
console.log(lat); // 0
console.log(lng); // 0
Notice how you can provide defaults for the nested object itself (= {}) and for properties within it (city = 'Unknown').
Key Takeaway: Apply default values at every nesting level where data might be missing to make your destructuring bulletproof—each = acts as a safety net at that specific depth.