question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Nested ternaries aren't bad, just misused

See original GitHub issue

The argument against nested ternaries is that they can make code more difficult to understand. But they can make code easier to understand if they are wielded properly. Instead of banning nested ternaries, require that they are formatted such that each line has a single condition and a single result, with the catch-all at the end:

// bad
const foo = maybe1 > maybe2
  ? "bar"
  : value1 > value2 ? "baz" : null;

// good
const foo =
  maybe1 > maybe2 ? "bar"
  : value1 > value2 ? "baz"
  : null;

This is similar to a switch statement that always breaks. With this pattern, it’s impossible to get lost in nested contexts. Once you’ve ruled out a line applying to the case you’re considering, you can safely forget it. It’s easier to understand than the solutions provided by the style guide right now, and also saves a memory allocation.

Here are some other examples where this pattern improves code:

// bad
let result;
if (operator === ‘+’) {
  result = left + right;
} else if (operator === ‘*’) {
  result = left * right;
} else if (operator === ‘-’) {
  result = left — right;
} else {
  result = left / right;
}

// good
const result =
  operator === ‘+’ ? left + right
  : operator === ‘*’ ? left * right
  : operator === ‘-’ ? left — right
  : left / right;
  • Less code.
  • Prefers const over let.
  • Avoids side effects (i.e. assigning value of variable outside block scope).
// bad
if (conditionA) {
  outcome1();
} else if (conditionB) {
  if (conditionC) {
    outcome2();
  } else {
    outcome3();
  }
} else {
  outcome4();
}

// good
conditionA ? outcome1()
: conditionB && conditionC ? outcome2()
: conditionB ? outcome3()
: outcome4();
  • Less code.
  • Less cognitive load.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:10
  • Comments:30

github_iconTop GitHub Comments

11reactions
ljharbcommented, Feb 1, 2018

First of all, things that are easily misused / are easy to improperly wield are bad.

A switch statement isn’t a good idea to use ever either, because you can easily forget to always break. In the future, switch statements will be discouraged by this guide as well. (Separately, memory allocation is irrelevant; JS is a memory-managed language, which means it’s not the developer’s business to think about it).

The pattern you’re suggesting still has the same issues with intuition about precedence, so it doesn’t address the problem. In particular, I don’t agree that any of your “good” examples are easier to read; you’re also abusing && for control flow. The if/else example is far better.

7reactions
okaybenjicommented, Feb 9, 2018

@mk-pmb Sure, you could write:

const getResult = (operator) => {
  if (operator === ‘+’) {
    return left + right;
  }
  if (operator === ‘*’) {
    return left * right;
  }
  if (operator === ‘-’) {
    return left — right;
  }
  return left / right;
};

const result = getResult(operator);

But this code is still much better:

const result =
  operator === ‘+’ ? left + right
  : operator === ‘*’ ? left * right
  : operator === ‘-’ ? left — right
  : left / right;

It’s easier to read and understand, takes less time to read and maintain, and has less surface area in which bugs can hide. The fact that it’s also much more performant is just the cherry on top.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Stop using nested ternary operators. Here's why. | by Ben Lmsc
Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, ......
Read more >
I shall never give up on forcing ternary statements down my ...
I don't agree with you that nesting ternaries is always bad and you should fail any code review where you see one. I've...
Read more >
We don't need a ternary operator - DEV Community ‍ ‍
As I was reading it, I was just thinking about how messed up programming is. I personally hate the ternary operator. It's a...
Read more >
conditional operator - To ternary or not to ... - Stack Overflow
If you are nesting ternary operators, format the code to make that nesting obvious. ... to set it to a value, then I...
Read more >
Clear is better than clever [pdf] - Hacker News
Or it might be in various branches of an 'if', which aren't being ... "Smart and clever" code, like using nested ternaries, demands...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found