Mmohebifar

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`).

javascripttypescriptstyleternaryif-else
Public
0 executions

Run locally

npx codemod javascript-prefer-ternary-over-simple-if-else

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; to target = condition ? a : b;
  • Rewrites if (...) return a; else return b; to return 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:

  • if statements without an else
  • Branches with more than one effective statement
  • Assignment branches with different targets or different operators
  • Assignment branches with non-identifier targets like obj[key] or arr[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 SequenceExpression or YieldExpression
  • Outer else if links: only standalone eligible if ... else pairs 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

Ready to contribute?

Build your own codemod and share it with the community.