Nested Ternary Expression

ID

javascript.nested_ternary

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

JavaScript

Tags

readability, simplification

Description

Reports a conditional expression cond ? a : b that contains another conditional expression in any of its three positions:

const label = isAdmin ? "admin" : isStaff ? "staff" : "guest";

const score = a > b
  ? (a > c ? a : c)
  : (b > c ? b : c);

Rationale

A single ternary trades a few words for terseness and is widely understood. Stacking them multiplies the cost of reading without giving anything back: the reader has to mentally re-bracket the operators (right-associativity, possible parentheses) and remember which branch they were tracing. The bug rate of nested ternaries is high enough that almost every modern style guide either bans or strongly discourages them.

Remediation

Lift the inner ternary out into either an if/else or a small helper, or use early returns:

function labelFor(user) {
  if (user.isAdmin) return "admin";
  if (user.isStaff) return "staff";
  return "guest";
}

function maxOfThree(a, b, c) {
  return Math.max(a, b, c);
}

For two-level cases, replacing nested ternaries with a lookup table is often even cleaner:

const LABEL = { admin: "admin", staff: "staff" };
const label = LABEL[role] ?? "guest";

Notes

The rule reports the inner ternary, not the outer one. A two-level nesting therefore produces one issue, a three-level nesting produces two, and so on. Parenthesised inner ternaries are still reported — parentheses make the precedence explicit but do not solve the readability problem.