Avoid complex conditionals using the ternary operator

Dattatray Kale
Technogise
Published in
2 min readAug 20, 2019

?: is a ternary operator introduced to write elegant if-else clause.

It is a concise way of writing simple conditionals. However, those should be easily understandable by any human. It should not be used to write deeply nested complex conditionals that hamper the readability.

When to use?

When you have very simple if-else that could be covered in a line and returns value.

Example:

Display text as “Weekend” if it’s a Sunday otherwise “Working day”

Another one:

Determine the restaurant to visit depending upon cash in your wallet.

When NOT to use?

As said earlier, they are used to simplify the conditional so that they add value and make code simple and elegant.

However, that does not mean you should blindly rewrite ALL if-else clause with the ternary operator. Please avoid them when expression becomes complex and difficult to understand.

Bad Example

The implementation of the fizz buzz generator.

const output = number % 3 === 0 && number % 5 === 0 ? "FizzBuzz" : number % 3 === 0 ? "Fizz" : number % 5 === 0 ? "Buzz" : number;

In my career, I have seen people writing deeply nested clauses using the ternary operator. I kept the above example to convey my thoughts.

The above snippet adds unnecessary mental mapping to remember and process each conditional and symbols ?: ?: ?: more like a machine.

Please don’t be a human code compressor.

Better alternative

Conventional if-else over ternary when a condition becomes complex.

Day by day, high-level languages are introducing more features so that developers could write more human-readable expressive code. We should keep this point in our mind and avoid a few things like writing deeply nested complex ternary conditionals. Instead, go for conventional control flow statements like if-else or if-return-early.

Thoughts mentioned in this post are based on my personal experience. It is just a guideline. IMO, we should be compassionate about our co-worker while writing the code and should avoid clever-complex clauses using ternary operators and rather should focus on elegance.

Originally published at https://beingcraftsman.com on July 18, 2019.

--

--

Dattatray Kale
Technogise

Software Craftsman & Cloud Engineer with 13+ years' expertise. Proficient in React, Angular, .NET, Node.js, Java, AWS, Azure. Proven leader in team building.