I recently stopped cold while writing a ReactJS component and experienced a very brief (albeit intense) existential crisis. I had just, without giving it excessive thought, used not just a ternary expression to determine what the component would render, but I also used a bang in my logical test.
First: My Beef With Ternaries
I learned early in my code journey about the value of legible code, of chasing the paradigm of self-documenting code, of explicitly indicating one’s intentions with a minimum of mental friction. This is largely why I resist writing ternary operations wherever possible, thinking that an item like this
var result = input > BASELINE ? "Input is above baseline" : input < BASELINE ? "Input is below baseline" : "Input matches baseline";
is a difficult-to-read unclear mess; whereas
var result = string.Empty;
if (input > BASELINE)
{
result = "Input is above baseline";
}
else if (input < BASELINE)
{
result = "Input is below baseline";
}
else
{
result = "Input matches baseline";
}
puts practically zero friction on the eyeballs and takes nearly zero effort to understand.
I can understand the desire to write as few lines of code as possible, for a lot of reasons we don’t have space to get into just now. But I don’t feel that brevity was a good enough reason to make something more difficult to read. Many pair partners can attest I have a tendency to start with a classic IF-ELSE block and resist refactoring it into something more brief.
Enter the “Bang”
I might have a strong distaste for ternaries, but I absolutely despise using bangs. The fact I feel compelled to take a moment and define what the hell it is for the less technical reader seems to summarize my issue with it–it’s an overly complex tool.
A “bang,” is simply an exclamation mark (“!”). In most (all?) programming languages, we use it to mean “Take the opposite of this bool (true/false) value.”
For instance, if I have a bool variable “isDarkMode” that equals TRUE, then “!isDarkMode” means FALSE.
Nice and confusing, yes? Thanks; I hate it. To be fair, I have seen cases where using a bang is the most elegant (or least messy) way to get what we want…but more often, I’ve found it to be a sign of lazy naming, poor coordination across application layers, or someone trying to be super clever. It just smells.
// Dark Mode is enabled when the UI element isn't toggled because it's wired backwards
var isDarkMode = !uiToggle.IsToggled;
if (!isDarkMode)
{
// set everything to light mode styles
}
else
{
// set everything to dark mode styles
}
You might think this is contrived, but I’ve looked at similar blocks of production code more than twice, going “Why does this make my skin crawl.” A couple quick refactors (like inverting the IF and ELSE to get rid of the need for the bang or renaming the variable so we can use the <uiToggle> the way it was written) will restore sanity…but suffice to say when I see “bang” I say “Oh dear.”
You May Ask, “What Changed?” I’ll Tell You…
I essentially learned to code in C#, and then spent the first years of my career primarily in the back end of .NET Framework applications. I relish the sense of order that comes with strongly typed objects backed by interfaces. Knowing I can extend these stable items whenever I needed new behavior (and knew they’d behave the same way over and over, or throw an exception trying).
More recently I’ve been adding functionality to a React web app (as you may have gathered from my opening paragraph). I’ll own it–JavaScript in general, and ReactJS in particular, were technologies that baffled me as I tried to become fluent in C#. The differences between a strongly typed language and the chaos of JS were bad enough–but React leverages the extreme flexibility of JS in ways I couldn’t comprehend.
For instance, the fact that when using a child component you can pass in one, some, all, or none of the properties defined or used in that child component without expressly providing overloads for the component. Try that in C# and see how fast your app blows up.
// Renders an empty view in light mode
<ChildComponent />
// Displays the list data in light mode, but does not render edit options because no user
<ChildComponent
dataList={list}
/>
// Displays the list data with all options, in dark mode
<ChildComponent
dataList={list}
userId={user.id}
darkMode
/>
The magic, and my existential crisis, happen inside the child component’s Render() function, thanks to how JavaScript handles resolving objects.
render() {
const { dataList, userId, darkMode } = this.props;
if (darkMode) {
setDarkModeClassNames();
}
return (
<React.Fragment>
{ !dataList
? // render empty display
: // render the list
}
{ userId &&
// render the edit/add options
}
</React.Fragment>
);
}
Because JS nor React will balk if any of those three properties are unassigned, we can (and should) take different actions depending on if there’s actually an object attached to that variable. React makes this easy enough with their conditional in-line rendering.
What we see here inside the logical operators is shorthand for “Is this defined?” and when we apply the bang “Is this NOT defined?” It’s checking both that the variable has been defined, and that it has been defined in a usable way (ie, dataList isn’t null). We could do this manually and explicitly…but that’s not good, idiomatic, or smart JavaScript. It’d be like writing one’s own “string.IsNullOrEmpty()” method instead of using the built in C# method.
You’ll see I open my first ternary with a bang (aren’t you glad you’re not paying for this content??). I did this because I felt, in this case, it IS the most explicit approach. I wanted to indicate what the next person in the file should pay the most attention to–the component cares if the listData is missing. We could invert this ternary and get the same result…but, I wanted to emphasize “The weird, early-return style behavior happens when there’s no list data.”
And yes. I’m using a ternary here, two if we count the neat short circuit with the userId. For one thing, I can break it up over several lines for clarity. For another, it would be significantly more work to replicate this behavior in a different pattern. It makes sense, and (based on the existing examples in the code base plus all the reading I did) it’s idiomatic React.
TL;DR…
I had a major polyglot growth moment. I embraced the features of a language that just wouldn’t fly in my “home” tech stack, and I added a whole mess of tools to my kit to use and reference going forward. What is nonsense in a typed language is totally fine in an untyped one, and that’s okay.