Disallow if
statements as the only statement in else
blocks
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) {
// ...
}
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();
}
Disable this rule if the code is clearer without requiring the else if
form.
This rule was introduced in ESLint v0.6.0.
© OpenJS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/latest/rules/no-lonely-if