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
Code Quality JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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