nestedStandaloneIfs
Reports
ifstatements that are the only statement inside anelseblock or inside anotherifwithout anelse.
✅ This rule is included in the tsstylisticandstylisticStrictpresets.
This rule identifies two patterns of unnecessarily nested if statements that can be simplified:
- Lonely
ifinelse: Anifstatement that is the only statement inside anelseblock can be written aselse if. - Lonely
ifinif: Anifstatement that is the only statement inside anotherif(without anelse) 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
ifhas anelseclause (for the “lonely if in if” pattern)
Examples
Section titled “Examples”Lonely if in else
Section titled “Lonely if in else”if (condition) { doSomething();} else { if (otherCondition) { doSomethingElse(); }}if (condition) { doSomething();} else if (otherCondition) { doSomethingElse();}Lonely if in if
Section titled “Lonely if in if”if (a) { if (b) { doSomething(); }}if (a && b) { doSomething();}Operator Precedence
Section titled “Operator Precedence”When combining conditions, the rule correctly handles operator precedence by adding parentheses where needed:
if (a || b) { if (c) { doSomething(); }}if ((a || b) && c) { doSomething();}When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.