Let's say you've got to position some element at the top of a page but that its top property will have to vary depending on the existence a couple other items that might also be up there. For instance, you want to position: sticky a menu bar but you have to contend with the possible presence of an announcement banner as well as the WP admin bar.
Not a big deal, right? Just check for their existence and get their heights. There are thusly four states to deal with: both items, one or the other, and neither. Assuming we've queried for them and gotten their heights should they exist, you might follow it up with a simple if block to position your menu bar.
let menuTop;
if ($admin && $banner) {
menuTop = hAdmin + hBanner;
} else if ($admin) {
menuTop = hAdmin;
} else if ($banner) {
menuTop = hBanner;
} else {
menuTop = 0;
}
Simple but a bit ugly. How could we simplify it at least visually if not in some more useful manner? I had computers turn this block of if stuff into a nested ternary statement.
let menuTop = $admin && $banner ? hAdmin + hBanner : $admin ? hAdmin : $banner ? hBanner : 0;
It's been condensed to one line, and that's sometimes nice, but it's not exactly readable or easy to parse what's happening. You could add some parentheses around the bits that are "asking" the state of things to assist in clarity.
let menuTop = ($admin && $banner) ? hAdmin + hBanner : ($admin) ? hAdmin : ($banner) ? hBanner : 0;
It's an improvement for sure, but perhaps you could add some line breaks and tabs or spaces to align things instead of one-lining it. A couple options for some realignment might look like the following.
let menuTop = $admin && $banner
? hAdmin + hBanner
: $admin
? hAdmin
: $banner
? hBanner
: 0;
let menuTop = $admin && $banner ?
hAdmin + hBanner
: $admin ?
hAdmin
: $banner ?
hBanner
: 0;
Either way it's still a bit of an algorithm to have to sort out in your head should you have to come back to this code later. And if you go for one of these last couple, you might as well just use the initial if block above since the ternary method takes about as much space but is somewhat less easy to understand at a glance.
Is there a better way? There is, in fact, and you can call it boolean arithmetic if you'd like since that sounds fancy.
let menuTop = ($admin ? hAdmin : 0) + ($banner ? hBanner : 0);
Instead of nesting ternaries into one statement or using a four-part if block, we use two separate ternary statements and add their results together. This covers all four or our possible states with just two statements, it's far more compact, and it's quite simple to look at this line later and see what it's doing.