This TypeError occurs when you try to destructure properties from a value that is null or undefined. Destructuring requires the right-hand side to be an object or array; null and undefined cannot be destructured.
Why it happens
- •A function or API call returns undefined when an object was expected.
- •An async data fetch has not resolved yet and the state is still undefined.
- •A conditional return path leaves the value undefined in some cases.
- •Destructuring from an optional function parameter that was not provided.
Examples
Code that triggers the error
function getUser() {
return undefined;
}
const { name, email } = getUser();Error output
TypeError: Cannot destructure property 'name' of undefined as it is undefined.
How to fix it
Provide a fallback with nullish coalescing: const { x } = getValue() ?? {}. Add a default value in the function signature: function fn({ x = 0 } = {}). Always initialize state to an empty object rather than undefined when awaiting async data.
Fixed code
function getUser() {
return undefined;
}
const { name, email } = getUser() ?? {};
console.log(name); // undefined (no throw)Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free