Mmohebifar

javascript-no-else-after-return-in-if

Flatten redundant `else` and `else if` branches after `return`, `throw`, `continue`, or `break` when the preceding `if` branch already exits the current control path.

javascripttypescripteslintcontrol-flowcleanup
Public
0 executions

Run locally

npx codemod javascript-no-else-after-return-in-if

javascript-no-else-after-return-in-if

Flattens redundant else and else if branches when the preceding if branch unconditionally exits with return, throw, continue, or break.

The codemod is intentionally conservative. It only rewrites if statements that are already inside a statement list, skips labeled break/continue, skips cases involving try/finally, and skips alternates that would hoist top-level declarations out of an else block.

What It Rewrites

js

becomes:

js

It also handles chained else if branches by repeatedly flattening the chain until no redundant else remains.

Target Files

  • **/*.{js,jsx,mjs,cjs} via the JavaScript parser
  • **/*.{ts,mts,cts} via the TypeScript parser
  • **/*.tsx via the TSX parser

Preserve / No-op Cases

  • The consequent does not exit on every path
  • The else body would hoist top-level declarations whose scope would change
  • Labeled break or continue
  • if statements inside try / finally flows where the codemod cannot safely prove equivalence
  • if statements that already have no else

Development

bash

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.