disallow if statements as the only statement in else blocks (no-lonely-if)

The --fix option on the command line can automatically fix some of the problems reported by this rule.

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:

/*eslint no-lonely-if: "error"*/

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

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

Examples of correct code for this rule:

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

Resources

Js中文网,专注分享前端最新技术、大厂面试题、聊点程序员轶事、职场感悟,做前端技术的传播者.

加入前端布道师交流群

扫描二维码回复 加群 学习,与大厂大佬讨论技术.

BAT面试题大全