Solve - Cannot destructure Property of Null Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by MD Duran

Solve - Cannot destructure Property of Null Error #

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

cannot destructure property of null

Here's an example of how the error occurs.

index.js
// ⛔️ Cannot destructure property 'name' of null // as it is null const {name} = null; function example(obj) { // ⛔️ Cannot destructure property 'num' of null // as it is null const {num} = obj; } example(null);

We tried to destructure a property from a null value, which caused the error.

Instead, provide a fallback of an empty object when destructuring.

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

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

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 null" error.

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

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

The fromDb variable stores a null 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 = null; const floor = fromDb?.country?.address?.floor; console.log(floor); // 👉️ undefined

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

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