javascript-prefer-ternary-over-simple-if-else
Convert simple, equivalent if-else statement pairs into conditional (?:) expressions in JavaScript/TypeScript to improve brevity and consistency with modern style rules (aligned with eslint-plugin-unicorn prefer-ternary).
Installation
bash
Usage
- Rewrites
if (...) target = a; else target = b;totarget = condition ? a : b; - Rewrites
if (...) return a; else return b;toreturn condition ? a : b; - Unwraps a single block layer on each branch before matching, so block-wrapped single statements are transformed too.
Supported files:
*.js,*.jsx,*.mjs,*.cjs,*.ts,*.tsx
Representative examples:
js
js
No-op cases:
ifstatements without anelse- Branches with more than one effective statement
- Assignment branches with different targets or different operators
- Assignment branches with non-identifier targets like
obj[key]orarr[i] - Mixed control flow like
return/throw - Branches inside single-statement blocks that contain comments the codemod cannot safely remap
- Branch statements that contain inline or trailing comments the codemod cannot preserve
- Ternary arms that are
SequenceExpressionorYieldExpression - Outer
else iflinks: only standalone eligibleif ... elsepairs are transformed
Comment handling is intentionally conservative. If a single-statement block contains branch-local comments outside the rewritten statement, the codemod leaves that if-else unchanged.
Development
bash
License
MIT