Ternary With Identical Branches
ID |
javascript.ternary_identical_branches |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
copy-paste, dead-code, reliability |
Description
Reports a conditional expression cond ? a : b where the two branches are textually identical:
const x = ready ? 1 : 1;
const y = ok ? doStuff() : doStuff();
The condition is evaluated for nothing — both branches produce the same result.
Rationale
A ternary that returns the same value in both branches almost always means one of:
-
the developer copy-pasted one branch and forgot to change it
-
the condition was left over after one branch was simplified, and now the whole expression is dead
Either way the conditional misleads readers, who reasonably assume ?: means the two sides differ.
Remediation
Replace the ternary with the branch itself:
const x = 1;
const y = doStuff();
If the branches were supposed to differ, fix whichever one is wrong:
const x = ready ? 1 : 0;
Notes
The rule fires only when the textual source of the two branches is identical (after trimming). Side effects in the condition are not considered: dropping the ternary may change behaviour if the condition is someFunction(), so the suggested fix above assumes a side-effect-free condition.