Destructuring undefined objects
Cannot destructure property X of Y as it is undefined.
You may have gotten this error before. It happens when trying to destructure properties from an object that can be undefined
. How can we destructure the properties of an object that might be undefined
?
Let's find out by looking at an example. Let's say we have an object called data
and we want to destructure the user
property from it. However, data
might return as undefined
from the method where we get it from.
const getData = () => undefined;
const data = getData();
const { user } = data;
console.log(user);
// ERROR
If we try running this code, we'll get the following error: "Cannot destructure property 'user' of 'data' as it is undefined."
To solve this, we can use short circuit evaluation to supply a default value in the case that data
is a falsy value, that is, null
or undefined
.
Let's apply short circuit evaluation using the logical OR operator, ||
.
const getData = () => undefined;
const data = getData();
const { user } = data || {};
console.log(user);
// undefined
If we now try running this updated code, we won't get the error anymore. We'll instead get undefined
logged to the console.
Short circuit evaluation is a programming concept where the execution of some sub-expression in a logical expression will be skipped.
Let's break down the short circuit evaluation in this example. In the expression data || {}
, if data
is not undefined
, then {}
is not evaluated. This is because the expression's result has already been determined to be data
. The empty object {}
is only evaluated when the data
object is a falsy value, that is, null
or undefined
.
In the example above, data
is undefined
. Thus, the expression data || {}
results in the empty object, {}
. Since the empty object has no user
property in it, the value of user
is undefined
.
We could have also used the nullish coalescing operator rather than the logical OR operator, ||
. Here's what that would look like.
const getData = () => undefined;
const data = getData();
const { user } = data ?? {};
console.log(user);
// undefined
The null nullish coalescing operator,
??
, is a logical operator that returns what's on it's right-hand side when its left-hand side isnull
orundefined
. If what is on its left-hand side does not evaluate tonull
orundefined
, then it will return what's on its left-hand side.