What's the ternary operator alternatives?
Personally, I liked ternary operator their awesome. However in my company we try to avoid nested ternaries.
For instance:
let optionA = false;
let optionB = true;
// NOT ALLOWED
<p style={{ fontSize: optionA ? '2rem' : optionB ? '3rem' : '1rem' }}>HEADER</p>
My approach is something like this.
const fontSize = (defaultOption = '1rem') => {
if (optionA) return '2rem'
if (optionB) return '3rem'
// add more...
return defaultOption
}
let optionA = false;
let optionB = true;
<p style={{ fontSize()}}>HEADER</p>
However, I'm thinking if there's an elegant way for this use case. I kind of thinking about lookup table or something else.
Any suggestion?
Posted Mar 26, 2022, 9:05 AM UTC
Ternary operator are ok. Nested ternary operator are just horrible most of the time (imho).
There are many ways to bypass that, one would be to create an object like
however in your case youre working with boolean values (which i wont recommend). Define something like 'small', 'medium', 'large' and then do the lookup.
I do not understand how useMemo helps here as u/jaunelacouleur stated because it just helps to memoize the value
Using a lookup/map is my favorite way to write options when I can get away with it! It’s a much more readable version of a switch statement and it’s quicker to write as well.
I really wish js had proper pattern matching!
It’s also the fastest of the three on most browsers