What's the ternary operator alternatives?

Discussion

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

2046
elchicodeallado•

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

const fontSizes = {
    optionA: '2rem',
    optionB: '3rem'
}

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

47
Phopaa•

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.

24
CheeseFest•

I really wish js had proper pattern matching!

2
[deleted]•

It’s also the fastest of the three on most browsers

1
TechnoEchoes•

There’s nothing wrong with an old fashion if/else if/else. Readable code is the most important thing. Your minifier will take care of the rest.

45
FilsdeJESUS•

This , READABILITY it is not just about you but for future readers

20
BlitzTech•

“Code spends 90% of its existence being read and 10% being written. Optimize accordingly”

Best advice I got when I was much earlier in my career.

27

My mind is blown on this Saturday morning.

1
campbellm•

Mostly, I'd say. Code is for humans, computers generally don't give a shit, so be optimize for people to the extent possible.

6
numinor•

The most important being that the future readers are likely going to be you, at various points in the future.

2
gHHqdm5a4UySnUFM•

Absolutely. Readability should be the priority here because you won’t remember this code 2 months from now. Or some junior dev will copy and paste your code and put some critical logic inside a nested ternary instead of just a trivial font size.

3
davidfavorite•

Your approach is perfectly fine. I also use switch/case when I have lots of options

9
Roguewind•

There are a few ways to go about this depending on the use case. If options A and B are string values that can be interpreted as object keys, then:

const DEFAULT_FONT_SIZE = '1 rem'
const FONT_SIZE_OPTIONS = {
  optionA: '2 rem',
  optionB: '3 rem'
}
const fontSize = FONT_SIZE_OPTIONS[option] ?? DEFAULT_FONT_SIZE

So, here, I'm defining default font size as a constant to prevent there being a "magic variable". Essentially, self-commenting code. Then the size options are defined in an object, and if the option key passed in returns undefined then you use the default option. Fairly simple.

Now, if there's actual logic involved based on the options...

const getFontSize = (options) => {
  const DEFAULT_FONT_SIZE = '1 rem'
  // do your logic/comparisons/whatever
  // return the value based on that logic
  // and if none of those are true, return the default size.
}

This is very similar to what you already have. The difference is that the parameter the function accepts is what it depends on from outside the function. This keeps the function pure.

7
mahade•

The setup is wrong. Inline CSS is to be avoided at all times except in very rare situations.

You're better off using tools like: https://www.npmjs.com/package/classnames

But first: Why is your font-size dependent on 2 different properties?

  1. Your <p> should have a default font-size of 1rem coming from your CSS reset and/or default theme file.
  2. Then your component just needs to figure out how to make sense of it all. And CSS specificity helps.

You could do that using (S)CSS modules or Styled Components. Quick code that I didn't test, but something like this:

type THeaderProps = {
  optionA: boolean;
  optionB: boolean;
};

const Header = styled('header')<THeaderProps>(
  ({ optionA, optionB }) => css`
    font-size: 1rem;

    ${optionA && css`
      font-size: 2rem;
    `}

    ${optionB && css`
      font-size: 3rem;
    `}
  `,
);

<Header {...[optionA, optionB]}>
  HEADER
</Header>

Very readable, TypeScript baked in, easy to see what's going on, and it allows you to easily theme things on the go as well; what if optionB in the future also changes the background-color? Now you can do whatever you want.

6
sQuar3x•

+1

This is the standard approach if you are not using styled-components or another css-in-js library.

2
chillermane•

Inline CSS is to be avoided at all times except in very rare situations.

I’ve created some mid size projects (15k lines) using styled components and using inline styles and I can tell you there are advantages to using purely inline styles. It’s not as black and white as people make it out to be.

Writing inline styles is much faster to begin with because you can easily create styles while writing your markup. If you use styled components you have to spend time going back and forth between the markup and the styling. You don’t have to name things with inline styles (which saves time as well).

Not saying it’s better or worse but inline styles have upside and it’s fine to use them

0
mahade•

I'm all for shades of gray in arguments, but inline CSS falls heavily under the "avoid as much as possible" part. Here's why:

  1. Inline CSS is hard to override with CSS specificity. You'll get !important hell on you.
  2. Inline CSS cannot be multi-line in normal HTML, results:
  • Git will think the entire line changed even if you change just one thing;
  • You can commit and omit individual lines in git, but not individual columns of characters;
  • It's harder to read because we're used to individual statements of code occupying their own line.
  • With tons of inline CSS and smaller IDE windows (Github editor, for example, or your terminal's nano or vim), things will automatically start wrapping.
  1. With your inline CSS spread all over the place, you'll have a harder time figuring out what's going on, styling-wise.
  2. You can't add media queries in inline CSS.

And I can go on and on...

You're thinking of tools like Tailwind that spam utility classes in the class attribute. I don't like Tailwind for that specific reason, but even they have tools available to take it into your own (S)CSS files by using @apply, at which point Tailwind actually becomes good:

https://tailwindcss.com/docs/reusing-styles#extracting-classes-with-apply

3
firstandfive•

Inline styles for faster prototyping is totally fine, but if you’re on a project already using styled components with at least one other maintainer, you should probably switch all your inline styles over to styled components before opening your PR unless you crave chaos.

1
bethevoid•

You can actually write styled-components styles inline with the markup. Check out the styled components Babel css plugin. Pretty much every CSS-in-JS library has an option like that.

1
Merad•

The problem isn't really ternary operators. Chained ternaries can sometimes be the most readable option when they aren't used inline and are well formatted. The problem, IMO, is the use of boolean flags. In your example there are 4 different permutations of input that are possible, but you're just ignoring one of them. If you add a third option, you'll have 9 possible inputs and ignore 5 of them, a fourth option will give 16 possible inputs and ignore 11 of them, etc. This makes it much more difficult for someone using your components (or functions, if you use this pattern with function arguments) to reason about the inputs because it's not obvious that there's a priority order (i.e. optionA overrides any other flag), or that setting some flags will have no effect if other flags are set. It also makes it much more likely for someone to make a mistake in mapping the flags to the real value, leading to a bug.

This is the type of problem that screams for enums. Unfortunately you don't have enums unless you're using Typescript, but in js it's reasonable to use strings instead. The end result is actually significantly cleaner because you only end up with one prop, and that prop's name and value are both descriptive:

const textSizeToFontSize = (size) => {
  switch (size) {
    case "xsmall":
      return "1rem";
    case "small":
      return "2rem";
    case "medium":
      return "3rem";
    // add more...
    default:
      throw new Error(`Invalid text size '${size}'`);
  }
};

const MyComponent = ({
  headerTextSize = "small",
  contextTextSize = "xsmall",
  content,
}) => {
  const headerStyle = useMemo(
    () => ({
      fontSize: textSizeToFontSize(headerTextSize),
    }),
    [headerTextSize]
  );
  const contentStyle = useMemo(
    () => ({
      fontSize: textSizeToFontSize(headerTextSize),
    }),
    [contextTextSize]
  );

  return (
    <>
      <p style={headerStyle}>HEADER</p>
      <p style={contentStyle}>{content}</p>
    </>
  );
};
6
Inatimate•

Why the usememo hook?

1
Merad•

You're constructing an object to pass down as a prop, so if you don't memoize it a new object will be constructed every time the component is rendered causing the child component to re-render even if none of the properties in the object actually changed. Arguably it's a premature optimization here since the child components are just html tags, but I did it out of habit.

1
Inatimate•

Got it thanks

1
achauv1•

I wish there would be some way to extend TypeScript's compiler with new AST parser/codegen to support :

  • expression conditionals (if, else)
  • pattern matching
  • hygienic macros (but only for codegen, not parsing)
2
TechnoCat•

You could have typescript be a compile target.

0
achauv1•

I wish tsc was architected more like babel

1
TechnoCat•

Babel and TypeScript have different goals. As soon as you start introducing new non-standard language syntax, tools like ESLint, IDE syntax highlighting, Prettier, etc. stop working.

1
achauv1•

I know they have different goal, tsc has a whole type checker built-in while babel is just parsing and codegen

2
TechnoCat•

The Do Expression proposal could help here: https://github.com/tc39/proposal-do-expressions

Extracting to a function, wrapping in an IIFE, or moving the computation to above the HTML/JSX could work too.

2
ArmchairSpartan•

Yeah this would be nice to have one day. I’d use it a lot.

1
dmethvin•

Well clearly you aren't thinking about job security, if statements are for chumps. This is what you want.

const fontSize = +optionA*1 + !+optionA*+optionB*2 + 1 + "rem";
<p style={{fontSize}}>HEADER</p>

Warning: If you use this your co-workers will hunt you down. It's the kind of code that you toss in as if it's a hand grenade.

2
gloriousReadOP•

Honestly, this is the worst code in the internet.

2
imihnevich•

Inside of JSX I sometimes use IIFE, but only when it's really better looking.

1
itsMalikDanial•

Just use a lot of && instead, they're more easier to read too

1
chillermane•

I always create a function at the bottom of the component file. In this case I’d call it “fontSizeForOptions(optionA, optionB)”. It would return the correct REM. This keeps your components nice and clean while also keeping the styling logic within the file (which is important).

Plus it makes it easier to use the function elsewhere if you happen to need the same style logic somewhere else

1
gloriousReadOP•

Highly appreciated if you can provide some code snippet.

1
CarrieAnneCoding•

The way you have it is just about as elegant as it gets. You could also create a map of values, something like:

const sizeMap = {
  optionA: '2rem',
  optionB: '3rem'
}

but in order to get that default return, you have to create a Proxy, which... might be too complicated for what you're trying to achieve.

1
zephyrtr•

Try to avoid? Most of the time? What is going on in this thread?

Nested ternaries are never necessary and always horrible. The point of a ternary is to make a very concise if/else statement. Nested ternaries is an absolutely brutal, wanton and avoidable abuse of the syntax.

1
HairbrainedScheme•

In general either a lookup table, switch statement or if/else is all ok.

For this specific instance, though, why is this even done in JavaScript? Put the option-name as a classname on the element and style it with css.

1

Using nested ternary operators is as bad as using goto statements in C or hard coding true in a while loop. Your first method is fine

0
saltamuros1•

🤦

-1
[deleted]•

[deleted]

-2
[deleted]•

if its either one then just use the simplified one

​

optionA ? '2rem' : '3rem'

-3

Same? 🤨

1
_Pho_•

useMemo or IIFE or a map

-12