src/content/docs/linter/rules/no-useless-else.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.3.0` - Diagnostic Category: [`lint/style/noUselessElse`](/reference/diagnostics#diagnostic-category) - This rule isn't recommended, so you need to enable it. - This rule has a [**safe**](/linter/#safe-fixes) fix. - The default severity of this rule is [**information**](/reference/diagnostics#information). - Sources: - Inspired from [`no-else-return`](https://eslint.org/docs/latest/rules/no-else-return) - Inspired from [`redundant_else`](https://rust-lang.github.io/rust-clippy/master/#redundant_else){
"linter": {
"rules": {
"style": {
"noUselessElse": "error"
}
}
}
}
Disallow else block when the if block breaks early.
If an if block breaks early using a breaking statement (return, break, continue, or throw),
then the else block becomes useless.
Its contents can be placed outside of the block.
If an if block breaks early using a breaking statement (return, break, continue, or throw),
then the else block becomes unnecessary.
This is because the content of the else block will never be executed in conjunction with the if block,
as the breaking statement ensures the control flow exits the if block immediately.
Therefore, the else block is redundant, and its content can be placed outside of the block,
reducing the indentation level by one.
while (x > 0) {
if (f(x)) {
break;
} else {
x++
}
}
function f(x) {
if (x < 0) {
return 0;
} else {
return x;
}
}
function f(x) {
if (x < 0) {
throw new RangeError();
} else {
return x;
}
}
function f(x) {
if (x < 0) {
return 0;
}
return x;
}
function f(x) {
if (x < 0) {
console.info("negative number");
} else if (x > 0) {
return x;
} else {
console.info("number 0");
}
}