I'm just wondering if someone out there has a more optimal, condensed way of doing this.
You have this backwards. More condensed is not more readable. The more operations are in one line the harder it is to figure out what it does:
a ?? b ? c ?? d?.e : f || x
Is much harder to parse mentally than if it wasn't all in one line. Among other things, you need to keep in mind the order of operations - does the OR mean (f || x) or is it OR-ing the entire expression up to there?
It will be resolved as (a ?? b ? c ?? d?.e : f) || x. Yet it hardly helps with evaluating this in your head.
The more optimal and readable way of writing this would be using regular if/else statements
let status;
if (person?.status == null)
status = 'Loading...';
else if (person.status)
status = 'Verified';
else
status = 'Not Verified';
If needed, it can be encapsulated in a function.
function status(person) {
if (person?.status == null)
return 'Loading...';
if (person.status)
return 'Verified';
return 'Not Verified';
}
If you really need something short to use, you can have a simple lookup table that resolves the different possible values:
const lookup = {
"null" : 'Loading...',
"true" : 'Verified',
"false": 'Not Verified',
}
/* ... */
const status = lookup[person?.status ?? null];
Also possible: drop the nullish coalescing operator and encode the undefined in the lookup:
const lookup = {
"null" : 'Loading...',
"undefined" : 'Loading...',
"true" : 'Verified',
"false" : 'Not Verified',
}
/* ... */
const status = lookup[person?.status];
This is mostly irrelevant but somewhat fun. You can combine a lookup and a function to make a fairly minimal function that does not use if/else or switch-es to determine what to return:
const status = person => ({
"null" : 'Loading...',
"undefined" : 'Loading...',
"true" : 'Verified',
"false" : 'Not Verified',
})[person?.status];
console.log( status() ); //Loading...
console.log( status(null) ); //Loading...
console.log( status({}) ); //Loading...
console.log( status({status: true}) ); //Verified
console.log( status({status: false}) ); //Not Verified
It is not the best practice but can be handy occasionally. It can aid prototyping things. It is then an easy refactor to extract the object out of the function which in turn would allow you to load it from configuration, for example. In this case it might help with translating this to different languages if you have something like
{
'english': {
"null" : 'Loading...',
"undefined" : 'Loading...',
"true" : 'Verified',
"false" : 'Not Verified',
},
'pig-lating': {
"null" : 'Oadinglay...',
"undefined" : 'Oadinglay...',
"true" : 'Erifiedvay',
"false" : 'Otnay Erifiedvay',
}
}