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 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)
if (condition) {
doSomething();
} else {
if (otherCondition) {
doSomethingElse();
}
}
if (a) {
if (b) {
doSomething();
}
}

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

if (a || b) {
if (c) {
doSomething();
}
}

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.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.