Skip to content
Advertisement

Alternative to nested ternary operator in JS [closed]

I personally love ternary operators, and in my humble opinion, they make complicated expressions very easy to digest. Take this one:

JavaScript

However in our project’s ESLINT rules nested ternary operators are forbidden, so I have to get rid of the above.

I’m trying to find out alternatives to this approach. I really don’t want to turn it into a huge if / else statement, but don’t know if there’s any other options.

Advertisement

Answer

Your alternatives here are basically:

  1. That if/else you don’t want to do
  2. A switch combined with if/else

I tried to come up with a reasonable lookup map option, but it got unreasonable fairly quickly.

I’d go for #1, it’s not that big:

JavaScript

If all the braces and vertical size bother you, without them it’s almost as concise as the conditional operator version:

JavaScript

(I’m not advocating that, I never advocate leaving off braces or putting the statement following an if on the same line, but others have different style perspectives.)

#2 is, to my mind, more clunky but that’s probably more a style comment than anything else:

JavaScript

And finally, and I am not advocating this, you can take advantage of the fact that JavaScript’s switch is unusual in the B-syntax language family: The case statements can be expressions, and are matched against the switch value in source code order:

JavaScript

How ugly is that? 🙂

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement