DEV Community

Discussion on: The Ternary Operator

Collapse
 
teamradhq profile image
teamradhq

Conditional operator is a short-hand for a ternary statement with one input and two outputs:

function foo(bar) {
  if (bar) {
    return 'baz';
  } else {
    return 'blitz';
  }  
}

Enter fullscreen mode Exit fullscreen mode

Sure, it's convenient for simple expressions like this to shorten them:

const foo = bar => bar ? 'baz' : 'blitz';
Enter fullscreen mode Exit fullscreen mode

At the same time though, we should consider that the ternary statement isn't necessary here:

function foo(bar) {
  if (bar) {
    return 'baz';
  }

  return 'blitz';
}
Enter fullscreen mode Exit fullscreen mode

I'd caution against using the conditional operator too often, and would never recommend nesting ternary statements in this manner. If you have to nest conditional operators, you're not writing a ternary statement.

Consider this an anti-pattern because this is not a ternary statement:

function tellMeIfItsHotOutside(outsideTempInCelsius) {
  return (
    (outsideTempInCelsius > 40) ? "Very hot; stay in" :
      (outsideTempInCelsius > 30) ? "Yeah, it is hot" :
        (outsideTempInCelsius > 25) ? "Kinda hot, but not too much" 
                : "It's actually really nice out"
  );
}
Enter fullscreen mode Exit fullscreen mode

^ This is clever code and its readability is entirely subjective. You can understand it, and I can understand it. A lot of people couldn't. And even with my experience, it took me a while to understand what was happening. For a while, I even thought that the last condition was a bug that would never be called.

In this case, a ternary statement isn't necessary or appropriate, because there is more than one input and more than two outputs.

Our truth table is more like this:

case temp result
0 > 40 "Very hot; stay in"
1 > 30 "Yeah, it is hot"
2 > 25 "Kinda hot, but not too much"
3 < 25 "It's actually really nice out"

That's one input and four outputs. Not really a ternary statement...

I'd suggest this would be more appropriate:

export function tellMeIfItsHotOutside(temp) {
  if (temp > 40) {
    return "Very hot; stay in";
  }

  if (temp > 30) {
    return "Yeah, it is hot";
  }

  if (temp > 25) {
    return "Kinda hot, but not too much";
  }

  return "It's actually really nice out";
}
Enter fullscreen mode Exit fullscreen mode

It's not clever, it's simple and stupid, and other developers will be able to comprehend it immediately. Given this is a self contained function, there's no ned to be concise or clever. We just need to be clear.

I've also renamed the variable temp because if we really need more information, such as unit of measurement, we can put it in documentation:

/**
 * @param   {number}  temp  The temperature in celcius
 * @return  {string}
 */
export function tellMeIfItsHotOutside(temp) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

I'd only recommend conditional operators where conciseness is beneficial to readability:

// higher order function
array.filter(n => condition ? 'yes' : 'no');

// template literal
const format = ({ correct }) => `Answer: ${correct ? 'correct' : 'incorrect' }`;

// component template
function SomeComponent(props: ComponentProps) {
  // ...

  return (props.isLoaded ? <PostContent props={...props}> : <Loading>);
}
Enter fullscreen mode Exit fullscreen mode

Use a ternary if your expression is simple and its logic takes the form of:

case result
true 1
false 0
Collapse
 
therealnrf profile image
therealnrf

Appreciate your detailed comment. I do agree with most of it. In fact, the only reason I included this operator in the series was because of its use in conditional rendering in React.

I did try to emphasize that its use was subjective. I've worked with programmers on both side of the fence. Some don't use it unless they have to, others don't really mind.

The nested example was necessary, in my opinion, just to show that it can be nested.

Collapse
 
damienpirsy profile image
Matteo Vignoli

Couldn't say it better. Also, ternary operators, like one-liners, sometimes are used just to show off some supposed programming skills - failing to understand that writing code that can be easily read is a way more appreciated and useful programming skill than codegolfing or saving a few spaces here and there.