⚡ Destructuring a Nested Property Throws an Error Instead of Just Returning Undefined
Accessing a deeply nested property that doesn’t exist normally just returns `undefined` in JavaScript – but destructuring the same nested path throws a `TypeError: Cannot destructure property ‘x’ of ‘undefined’ as it is undefined` instead, because destructuring has to actually READ each intermediate level to pull values out of it, and reading a property OFF of `undefined` is where the error comes from – not the final missing property itself.
🔎 The Problem
const response = { data: null };
const { data: { user } } = response;
// TypeError: Cannot destructure property '"'"'user'"'"' of '"'"'response.data'"'"'
// as it is null.
// Compare to plain property access, which does NOT throw:
const user2 = response.data?.user; // undefined, no error - if optional
// chaining is used
const user3 = response.data.user; // ALSO throws here, for the same
// reason - reading .user off null
// fails regardless of destructuring
✅ Fix: Default Values or Optional Chaining, at the Right Level
- Give the intermediate level a default value directly in the destructuring pattern: `const { data: { user } = {} } = response;` – the `= {}` provides a fallback specifically for when `data` itself is `null`/`undefined`, letting the destructuring of `user` proceed safely against an empty object instead.
- For deeper or more variable nesting, plain optional chaining before destructuring is often clearer: `const user = response.data?.user;` – it reads more explicitly as “this path might not exist” than a nested destructuring default does.
⚠️ The Rule to Remember
- The error isn’t really about destructuring specifically – it’s the same “cannot read property of null/undefined” error JavaScript always throws for that access pattern; destructuring just makes it easier to trigger accidentally, since the intermediate access is implicit rather than an explicit `.` you’d naturally think to guard.
- Destructuring defaults (`= {}`) only kick in when the value is exactly `undefined` – NOT for `null`. A field that’s explicitly `null` (common for “intentionally empty” API responses) still needs its own explicit handling, since `= {}` alone won’t catch it.
Destructuring doesn’t create a new way to fail – it just makes the same ‘reading a property off nothing’ failure easier to trigger without noticing.
