Writing conditionals in JavaScript using optional chaining
— JavaScript — 2 min read
In my current role as a front end developer, I build and maintain a lot of features that involve querying for data in our database, and rendering React components based on the results of my queries. Pretty standard stuff.
When defining the data, I handle it using the optional chaining operator (?.). In a nutshell, using the optional chaining operator allows you to read a property's value even if it's nested deep in a chained object without checking to see whether each property in the chained object is valid or not. If at any point a property is null
or undefined
, it immediately stops reading the chained object and returns the chained object as undefined
. This is super useful to prevent your chained object from returning a type error and causing a bug in your code.
For example, if I were trying to access data.user.name
without optional chaining, and the user
property was undefined
, I would get the following error:
const name = data.user.name;
console.log(name);
// Uncaught TypeError: data is undefined
Now, if I were to add optional chaining to the name
variable, it would immediately return undefined
instead if the user
property was undefined
.
const name = data?.user?.name;
console.log(name);
// undefined
Neat, right?
Recently, I was writing a conditional check to render a component based on data being returned in the form of an array. I was originally handling the data like so:
const renderComponent = () => {
if (!data || !data.length) return null;
return <Component />;
};
This was fine and all, and did the job, but it was suggested that I could make the code more concise by writing the following:
const renderComponent = () => {
if (!data?.length) return null;
return <Component />;
};
So how does this work?
By checking for !data?.length
instead of !data || !data.length
, I'm just consolidating the conditional checks. If data
was nullish (undefined
or null
), then the value of data?.length
would immediately return undefined
, which meant that !data?.length
would be true
, and my render function would return null
. If the data
property was valid, then it would check for the length of the array before rendering the component. The outcome is essentially the same, but it's simpler and more concise.
It took me a while to fully understand this, but when it did, it blew my mind. Try it out the next time you have to write a conditional based on data being queried.
If you have any questions or notice an error in this post, drop me a line at [email protected].