Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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 || {};
.
Here are 2 examples of how the error occurs.
// ⛔️ 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.
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).
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.
function test(obj = {}) { const {country} = obj; console.log(country); // 👉️ undefined } test(); test(undefined);
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
.
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.
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
).