Solve - Cannot destructure Property of Undefined Error in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Solve - Cannot destructure Property of Undefined Error #

The "Cannot destructure property of undefined" error occurs when we try to destructure a property from a value that is equal to undefined. To solve the error provide a fallback when destructuring the property, e.g. const {name} = undefined || {};.

typeerror cannot destructure property of undefined

Here are 2 examples of how the error occurs.

index.js
// ⛔️ Cannot destructure property 'name' of undefined // as it is undefined const {name} = undefined; function test(obj) { // ⛔️ Cannot destructure property 'country' // of undefined, as it is undefined const {country} = obj; } test();

We tried to destructure a property from an undefined value which caused the error.

To solve the error, provide a fallback of an empty object when destructuring, or set a default value for the parameter if using functions.

index.js
const {name} = undefined || {}; console.log(name); // 👉️ undefined function test(obj = {}) { const {country} = obj; console.log(country); // 👉️ undefined } test(); test(undefined);

We used the logical OR (||) operator. The operator returns the value to the right if the value to the left is falsy (e.g. undefined).

The falsy values in JavaScript are: null, undefined, 0, false, "" (empty string), NaN (not a number).

We return an empty object if any of the six aforementioned values is to the left of the logical OR (||) operator.
index.js
const {name} = undefined || {}; console.log(name); // 👉️ undefined

This helps us to avoid the "Cannot destructure property of undefined" error.

We defined a function with a default parameter in the second example.

index.js
function test(obj = {}) { const {country} = obj; console.log(country); // 👉️ undefined } test(); test(undefined);
The function gets passed the default parameter value if an argument is not provided, or an undefined value is supplied when calling the function.

Alternatively, you can use the optional chaining operator (?.) which short-circuits, instead of throwing an error, if the reference is undefined or null.

index.js
const fromDb = undefined; const name = fromDb?.name; console.log(name); // 👉️ undefined const obj = {name: 'Tom'}; const n = obj?.name; console.log(n); // 👉️ "Tom"

The fromDb variable stores an undefined value, so we short-circuit returning undefined instead of throwing an error.

If the reference is not nullish, the operator returns the corresponding value.

You can use the optional chaining operator to access deeply nested properties.

index.js
const fromDb = undefined; const floor = fromDb?.country?.address?.floor; console.log(floor); // 👉️ undefined

This approach helps us avoid getting an error when the reference is nullish (null or undefined).

Use the search field on my Home Page to filter through my more than 3,000 articles.