unicorn/no-nested-ternary

Disallow deeply nested ternaries, and require parentheses around a ternary in a ternary

fixable

In a ? b : c ? d : e, it's hard to see which : belongs to which ?. This rule allows one ternary inside another if the inner one is in parentheses. A third level is always reported.

--fix adds the parentheses. It doesn't rewrite a third level.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/no-nested-ternary" = "error" # or "warn"

Examples#

example.js1 problem
const size = width > 1200 ? "large" : width > 600 ? "medium" : "small";
example.js1 problem
const size = width > 1200 ? "large" : (width > 600 ? "medium" : (width > 300 ? "small" : "tiny"));
example.jsNo problems
const size = width > 1200 ? "large" : (width > 600 ? "medium" : "small");

For more than two levels, use if statements:

example.jsNo problems
function sizeOf(width) {
  if (width > 1200) return "large";
  if (width > 600) return "medium";
  return width > 300 ? "small" : "tiny";
}