prefer-ternary
UnreleasedConfiguration
Rule Details
This rule flags simple if statements that return or assign a value and
suggests replacing them with a ternary expression. A separate branch
collapses let x = a; if (test) { x = b; } into a single
const x = test ? b : a; declaration (or let x = … when the variable
gets a later write).
The motivation is that if-else statements typically produce more lines
than a ternary, leading to a larger, harder-to-maintain codebase. They can
also force developers to use let or var for variables that only get
reassigned, which unnecessarily introduces mutability and blocks
prefer-const from flagging the variable.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
Options
Type: string
Default: 'always'
'always'(default) — Always report supportedIfStatementreturns and assignments where a ternary can be used.'only-single-line'— Only report when the condition and the merged expressions fit on a single line.
Example with 'only-single-line':
Differences from ESLint
The upstream unicorn/prefer-ternary rule is reported under
eslint-plugin-unicorn's recommended and unopinionated configs and
auto-fixes via --fix. The current port reproduces that contract:
- The simple
if/elseform is rewritten to a ternary and the result is reported with a single diagnostic whosefixrewrites the source. - The
let x = a; if (test) x = b;form is reported with a diagnostic whosesuggestrewrites the source toconst x = test ? b : a;(orletwhen the variable receives a later write).