Mastering the Ternary Operator: Lessons from a Job Interview
When I interviewed for my current job, I participated in a Zoom meeting with three developers about a variety of topics in web development, but mostly about React. One of them asked me the following question:
Can you tell me about the ternary operator and how you would use it with React?
My reply was initially perfectly adequate, I think, as I described a line of code similar to this one:
{ condition ? <jsx if true> : <jsx if false> }
Most of us have seen this type of one-liner in React, and it is succinct and very readable.
However, I have also seen and written ternary operators that look like the code below for a modal on a client website (using React and Chakra-UI):
{metadata.name.search("Client Name") !== -1 ? (
<GridItem>
<Text pb='3px'>{rewardRatesNames[rarity]}</Text>
<Text>{rewardRates[rarity]/100}</Text>
</GridItem>
) : (
<GridItem>
<Text pb='3px'>{rewardRates2Names[rarity]}</Text>
<Text>{rewardRates2[rarity]}</Text>
</GridItem>
)}
I find the ternary syntax much harder to read when it spans many lines. The first clue that I have that I'm seeing a conditional is scanning over to the !== -1 ? (
on the first line, which isn't the most obvious thing to me.
So I attempted to explain to my interviewers something like the code I had written below for a client's website, which is a format that I find more readable.
const renderConnectedContainer = () => {
if (!account) {
return (
<div className="connected-container">
<button
className="cta-button submit-account-button"
onClick={createAccount}
>
Create Account
</button>
</div>
);
}
else {
return (
<>
<p className="instructions-text">
Some instructions
</p>
<div className="connected-container">
20 lines of JSX
</div>
</>
)
}
}
To me, the if-then-else structure is much easier to read and scan. Sure, there are more lines of code than a 1 line ternary, but they are easier to read than a multi-line ternary. At least to me!
However, after I had explained using an if-then-else
statement, one of the developers said to me:
Yes, but you can only use the ternary operator in JSX.
While I had to acknowledge that this statement is true, I did feel somewhat like I had been reciting "Jabberwocky" in giving my explanation of how to use if-then-else
via Zoom call without sharing my screen. I had failed to explain that I was discussing a preference for how to use conditionals. In other words, I went off on a tangent during my interview!
Fortunately, my tangent wasn't egregious enough not to get the job, but it did teach me a valuable lesson: one can have one's preferences, but it is best to stick to "the facts" in an interview!