loading...

An Alternative Ternary

samholmes profile image Sam Holmes Updated on ・2 min read

Like many languages, JavaScript has the conditional (ternary) operator. What's wonderful about this operator is that it can be nested in expressions and it returns a value. This is a good thing for functional programming and composability.

However, sometimes you don't need the second "falsey" part of the condition, so you end up with a placeholder for the false condition. This is reflected in React/JSX quite often:

return (<div>
  {confirm ? (
    <p>Your action has been done</p>
  ) : (
    ''
  )}
</div>)

It's like forcing the programmer to use else for every time he or she uses if.

The Alternative

The alternative to the ternary operation is to use the && (AND) operation.

return (<div>
  {confirm && (
    <p>Your action has been done</p>
  )}
</div>)

Because the AND operator will short-circuit if the left-operand is falsey, it acts identically to the first part of the ternary operator.

What's even more interesting is that we can combine the AND operator with || (OR) to get the same effect as the ternary operator:

return (<div>
  {confirm && (
    <p>Your action has been done</p>
  ) || (
    ''
  )}
</div>)

This means that we can easily extend a statement with one conditional concern to two concerns.

We don't stop there. We can embed these AND/OR statements just like we could with ternary.

return (<div>
  {isHappy && (
    <p>I'm feeling good</p>
  ) || (
    isHungry && (
      <p>I'm feeling hangry</p>
    ) || (
      <p>I'm feeling sad</p>
    )
  )}
</div>)

As you can see, && and || map to if and else pretty respectively. Wonderful!

Gotchas

A couple of things to note if you decide to use this pattern.

  1. Parentheses are important. The rule is to always wrap your outcome expression: condition && (outcome) || (outcome). Doing so will allow you to nest more conditional expression within the outcome expressions clearly. Note, it is not necessary if you do not intend to nest more conditional expressions.
  2. What the expression evaluates to may not be expected. For example: var selectedItem = selectedItemId && items[selectedItemId] In this case you might be tempted to think that selectedItem === undefined in the case that selectedItemId is falsey. Incorrect. Rather, selectedItem === selectedItemId. This is because an && operation evaluates to the either the last truthy value or the first falsey value (such is the case in the example). Such incorrect expectations should be accompanied with a explicit outcome for a falsey value: var selectedItem = selectedItemId && items[selectedItemId] || undefined

Naming the Pattern

This pattern needs a good name to go by so teams can decide whether to adopt this pattern. Let's go with:

Short-Circuit Conditionals (SCC)

Posted on by:

samholmes profile

Sam Holmes

@samholmes

Passionate Sourcerer of the Web and JavaScript

Discussion

markdown guide