No Nested Ternary

This article introduces the no-nested-ternary rule, including its advantages, implementation details, and relevant resources. These steps can help improve efficiency when avoiding nested ternary expressions.

May 23, 2020 · 1 min read · 120 Words · -Views -Comments · Programming

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.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover