Solve - Cannot destructure Property of Undefined Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Elio Santos

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

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.

Instead, 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, which 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).

If any of the six aforementioned values is to the left of the logical OR (||) operator, we return an empty object, which would allow us to avoid the "cannot destructure property of undefined" error.

In the second example, we declared the function with a default parameter.

Default function parameters allow us to specify a default value for a parameter, in case the parameter is not provided or an undefined value is provided 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, otherwise the operator returns the value that corresponds to the property.

You can use the operator for property access as many times as needed.

index.js
const fromDb = undefined; const floor = fromDb?.country?.address?.floor; console.log(floor); // ๐Ÿ‘‰๏ธ undefined

This approach prevents us from getting an error when the reference is equal to undefined or null.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee