No Nested Ternary

· 1 min read

Ternary expressions are quite concise when used for simple conditional value assignment, but when encountering nested logic, readability becomes very poor. In actual projects, I require the team to => disable them.

var foo = bar ? baz : qux === quxx ? bing : bam;

no-nested-ternary

To constrain the existence of such code, we add no-nested-ternary in eslint.

Rule introduction click here

Of course, for readability, we can add parentheses to improve it, but practice shows this doesn’t solve the problem. So, it’s not recommended.

So how should we write equivalent replacements for this type of logic?

Equivalent Replacement Methods

  1. if else
  2. switch
  3. Strategy pattern, building strategy objects

The above methods can replace our original nested ternary expression writing.