Disallow if as the Only Statement in an else Block (no-lonely-if)

If an if statement is the only statement in the else block of a parent if statement, it is often clearer to combine the two to using else if form.

if (...) {
    ...
} else {
    if (...) {
        ...
    }
}

should be rewritten as

if (...) {
    ...
} else if (...) {
    ...
}

Rule Details

This rule warns when an if statement’s else block contains only another if statement.

The following patterns are considered warnings:

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

The following patterns are not considered warnings:

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

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 0.6.0.

Resources