Skip to content

nestedStandaloneIfs

Reports if statements that are the only statement inside an else block or inside another if without an else.

✅ This rule is included in the ts stylistic and stylisticStrict presets.

This rule identifies two patterns of unnecessarily nested if statements that can be simplified:

  1. Lonely if in else: An if statement that is the only statement inside an else block can be written as else if.
  2. Lonely if in if: An if statement that is the only statement inside another if (without an else) can have its conditions combined with &&.

Both patterns reduce nesting and improve code readability.

Note that this rule will not flag cases where:

  • There are comments inside the block (indicating intentional structure)
  • Multiple statements exist in the block
  • The outer if has an else clause (for the “lonely if in if” pattern)
AE53 (condition)< {d ivclassNa="meec-li">nt< sp ansty="le--0:#82AAFF;--1:#3B61">B0doSomethi53(<);d ivclassNa="meec-li">53<} sp ansty="le--0:#C792EA;--1:#8844">AEel53< {d ivclassNa="meec-li">nt< sp ansty="le--0:#C792EA;--1:#8844">AE53 (otherCondition)< {d ivclassNa="meec-li">nt < sp ansty="le--0:#82AAFF;--1:#3B61">B0doSomethingEl53(<);d ivclassNa="meec-li">53< sp ansty="le--0:#D6DEEB;--1:#403F">5<3}d ivclassNa="meec-li">5<3}d ivclassNa="meco"><}d>
443F53 (conditiode61B0doSomet3F5<3() ;divclass="Nameec-">3F<53} spans="tyle--0:#C792EA;--1:#88">44AE3443F53 (otherConditiode61B0doSomething3F5<3() ;divclass="Nameec-">3<);>
AE53 (a)< {d ivclassNa="meec-li">nt< sp ansty="le--0:#C792EA;--1:#8844">AE53 (b)< {d ivclassNa="meec-li">nt < sp ansty="le--0:#82AAFF;--1:#3B61">B0doSomethi53(<);d ivclassNa="meec-li">53< sp ansty="le--0:#D6DEEB;--1:#403F">5<3}d ivclassNa="meec-li">5<3}d ivclassNa="meco"><}d>
443F53< (a spans="tyle--0:#C792EA;--1:#88">443F53 de61B0doSomet3F5<3() ;divclass="Nameec-">3<);>

When combining conditions, the rule correctly handles operator precedence by adding parentheses where needed:

AE53 (AE<||sp ansty="le--0:#D6DEEB;--1:#403F">53 b)< {d ivclassNa="meec-li">nt< sp ansty="le--0:#C792EA;--1:#8844">AE53 (c)< {d ivclassNa="meec-li">nt < sp ansty="le--0:#82AAFF;--1:#3B61">B0doSomethi53(<);d ivclassNa="meec-li">53< sp ansty="le--0:#D6DEEB;--1:#403F">5<3}d ivclassNa="meec-li">5<3}d ivclassNa="meco"><}d>
443F53 <((a spans="tyle--0:#C792EA;--1:#88">443F53< b) spans="tyle--0:#C792EA;--1:#88">443F53 de61B0doSomet3F5<3() ;divclass="Nameec-">3<);>

If you prefer explicit nesting for clarity in complex conditional logic, or if your codebase has a style guide that prefers the nested form, you may want to disable this rule.