ESLint v8.x reached end-of-life on 2024-10-05 and is no longer maintained. Upgrade or consider long-term support options
Versions

no-lonely-if

Disallow if statements as the only statement in else blocks

🔧 Fixable

Some problems reported by this rule are automatically fixable by the --fix command line option

If an if statement is the only statement in the else block, it is often clearer to use an else if form.

if (foo) {
    // ...
} else {
    if (bar) {
        // ...
    }
}

should be rewritten as

if (foo) {
    // ...
} else if (bar) {
    // ...
}

Rule Details

This rule disallows if statements as the only statement in else blocks.

Examples of incorrect code for this rule:

Open in Playground
/*eslint no-lonely-if: "error"*/

if (condition) {
    // ...
} else {
    if (anotherCondition) {
        // ...
    }
}

if (condition) {
    // ...
} else {
    if (anotherCondition) {
        // ...
    } else {
        // ...
    }
}

Examples of correct code for this rule:

Open in Playground
/*eslint no-lonely-if: "error"*/

if (condition) {
    // ...
} else if (anotherCondition) {
    // ...
}

if (condition) {
    // ...
} else if (anotherCondition) {
    // ...
} else {
    // ...
}

if (condition) {
    // ...
} else {
    if (anotherCondition) {
        // ...
    }
    doSomething();
}

When Not To Use It

Disable this rule if the code is clearer without requiring the else if form.

Version

This rule was introduced in ESLint v0.6.0.

Resources

Change Language