DEV Community

Cover image for Don't nest ternary operators. Please!
Accreditly
Accreditly

Posted on • Originally published at accreditly.io

Don't nest ternary operators. Please!

In JavaScript, the ternary operator (also known as the "conditional operator") is a concise and handy tool for conditional logic. However, when it comes to nesting these operators, you might be stepping into a tangled web of complexity. Let's discuss why nesting ternaries can be problematic and explore alternative approaches for cleaner code.

Understanding Ternary Operators

A ternary operator in JavaScript is a one-liner alternative to an if-else statement. It takes three operands: a condition, a result upon the condition being true, and a result if it's false.

Syntax:

condition ? exprIfTrue : exprIfFalse;
Enter fullscreen mode Exit fullscreen mode

Example:

let isAdult = age >= 18 ? 'Yes' : 'No';
Enter fullscreen mode Exit fullscreen mode

The Temptation of Nesting Ternaries

Nesting ternary operators means using one ternary inside another. It's often seen as a shortcut to handle multiple conditions.

Example of Nested Ternaries:

let category = age > 18 ? (age > 65 ? 'Senior' : 'Adult') : 'Minor';
Enter fullscreen mode Exit fullscreen mode

While this might seem like an efficient use of space, it introduces several issues.

1. Readability Concerns

Nested ternaries can quickly become hard to read and understand, especially for someone new to the code. What seems straightforward to you now might be a puzzle for future-you or other developers.

Hard-to-Read Example:

let message = user.isAuthenticated ? (user.hasPremium ? 'Welcome, premium user!' : 'Welcome, user!') : 'Please log in.';
Enter fullscreen mode Exit fullscreen mode

2. Debugging Difficulties

Debugging nested ternaries can be challenging. Isolating which part of the ternary chain is causing an issue is more complex than debugging a simple if-else statement or a switch case.

3. Maintainability Issues

As your codebase grows and evolves, maintaining nested ternaries becomes problematic. Any modification might require a significant unraveling and reworking of the logic.

4. Performance Misconception

Some developers might think nesting ternaries is faster or more efficient. However, any performance gains are negligible and certainly not worth the trade-off in readability and maintainability.

Alternatives to Nested Ternaries

1. Simple If-Else Statements:

   For clarity and ease of understanding, a traditional if-else structure is often best.


   let category;

   if (age > 18) {
       category = age > 65 ? 'Senior' : 'Adult';
   } else {
       category = 'Minor';
   }

Enter fullscreen mode Exit fullscreen mode

2. Switch Statements:

   For multiple conditions, a switch statement can be more readable.


   switch (true) {
       case age > 65:
           category = 'Senior';
           break;
       case age > 18:
           category = 'Adult';
           break;
       default:
           category = 'Minor';
   }

Enter fullscreen mode Exit fullscreen mode

3. Function Abstraction:

   Encapsulate complex logic in a function for better abstraction and reusability.


   function getCategory(age) {
       if (age > 65) return 'Senior';
       if (age > 18) return 'Adult';
       return 'Minor';
   }

Enter fullscreen mode Exit fullscreen mode

While ternary operators are a useful feature of JavaScript, nesting them can lead to code that's hard to read, debug, and maintain. Opting for clearer, more straightforward alternatives like if-else statements, switch statements, or function abstraction makes your code more accessible and maintainable. Remember, in programming, clarity should almost always trump cleverness. Production code isn't code golf, shorter isn't always better.

Top comments (5)

Collapse
 
sreno77 profile image
Scott Reno

Yeah nested ternaries are a bad idea in any language

Collapse
 
accreditly profile image
Accreditly

Absolutely, it's not specific to any one language. I used JS as it's the most easily understood syntax, but it definitely applies everywhere.

Collapse
 
hassan_dev91 profile image
Hassan

Let me offer another solution for ternary: You can define a function as an abstraction:

function ternary(cond, truthyValue, falsyValue) {
  return cond ? truthyValue : falsyValue
}

function getCategory(age) {
  const firstTernary = ternary(age > 65, 'Senior', 'Adult')
  return ternary(age > 18, firstTernary, 'Minor')
}

console.log(getCategory(16)) // Minor
console.log(getCategory(30)) // Adult
console.log(getCategory(75)) // Senior
Enter fullscreen mode Exit fullscreen mode
Collapse
 
accreditly profile image
Accreditly

That is interesting. It's certainly more readable that a nested ternary, but is it more readable than using a switch statement?

You'd also run into trouble introducing a third condition there, as readability would deteriorate exponentially as you added more conditions.

Collapse
 
hassan_dev91 profile image
Hassan

That's correct, switch statement is more readable in this case. You know we can handle it better than switch statement by functional or even object oriented paradigm.