Should You Use the Ternary Operator in Programming?

October 29, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

I recently came across an interesting thread discussing the ternary operator. As someone who works extensively with frontend code, I find this topic particularly relevant because it touches on a fundamental tension in programming: the trade-off between concise code and readable code.

Let's start with the basics. MDN (Mozilla Developer Network, the unofficial bible for web developers) defines the ternary operator as JavaScript's only operator that takes three operands.

It’s structured as condition ? exprIfTrue : exprIfFalse, executing exprIfTrue if the condition is true (truthy) and exprIfFalse otherwise." This operator is often considered a shorthand for the if statement.

Here's a simple example. Say you have a getFee function that returns a different price based on membership status: $2 for members and $10 for non-members. The traditional way to write this would be:

function getFee(isMember) {
  if (isMember) {
    return "$2.00";
  } else {
    return "$10.00";
  }
}

Using the ternary operator, you can compress this into a single line:

function getFee(isMember) {
  return isMember ? "$2.00" : "$10.00";
}

But here's where it gets interesting - and potentially problematic. While the ternary operator can make simple conditions more elegant, it can quickly turn into what programmers call "write-only code" - code that's easy to write but impossible to read.

This is especially true when you start nesting ternary operators. It's so problematic that ESLint (a popular tool that helps maintain code quality) has a specific rule called no-nested-ternary to prevent code like this:

foo ? (baz === qux ? quxx() : foobar()) : bar();

The debate gets even more nuanced in React development. Consider this common pattern for rendering lists. This code has a subtle bug: if members.length is 00 && something returns 0, which renders as 0 on the page.

<div>
  {members.length &&
    members.map((member) => <div key={member.id}> {member.name} </div>)}
</div>

Some developers prefer using the ternary operator to fix this:

<div>
  {members.length
    ? members.map((member) => <div key={member.id}> {member.name} </div>)
    : null}
</div>

But there's a third approach that many consider more readable: extracting the logic into a separate component:

function MemberList({ members }: MemberListProps) {
  if (members.length === 0) {
    return null;
  }

  return (
    <div>
      {members.map((member) => (
        <div key={member.id}> {member.name} </div>
      ))}
    </div>
  );
}

This debate isn't unique to JavaScript. Different programming languages have taken different approaches. JavaScript's ternary syntax follows the C language model (? and :), which some find overly abstract. Python, by contrast, uses if...else inline for readability: '$2.00' if isMember else '$10.00'.

Go, on the other hand, made the radical choice to not support ternary operators at all, arguing that they often lead to unreadable code.

The bottom line? Code is a tool for communication, not just computation. The ternary operator is like salt in cooking - useful in moderation, harmful in excess. Rather than seeing it as inherently good or bad, consider context: use it where it clarifies your code and skip it where it doesn't. After all, the goal isn't to write the shortest possible code, but the most maintainable code.

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee