Skip to content

noUselessElse

诊断类别:lint/style/noUselessElse

¥Diagnostic Category: lint/style/noUselessElse

自从:v1.3.0

¥Since: v1.3.0

来源:

¥Sources:

if 块提前中断时禁止 else 块。

¥Disallow else block when the if block breaks early.

如果 if 块使用中断语句(returnbreakcontinuethrow)提前中断,则 else 块变得无用。其内容可以放在块之外。

¥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 块使用中断语句(returnbreakcontinuethrow)提前中断,则 else 块变得没有必要。这是因为 else 块的内容永远不会与 if 块一起执行,因为中断语句确保控制流立即退出 if 块。因此,else 块是多余的,其内容可以放在块之外,从而将缩进级别减少一级。

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

¥Examples

¥Invalid

while (x > 0) {
if (f(x)) {
break;
} else {
x++
}
}
code-block.js:4:7 lint/style/noUselessElse  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This else clause can be omitted because previous branches break early.

2 │ if (f(x)) {
3 │ break;
> 4 │ } else {
^^^^^^
> 5 │ x++
> 6 │ }
^
7 │ }
8 │

Unsafe fix: Omit the else clause.

2 2 if (f(x)) {
3 3 break;
4 - ····}·else·{
4+ ····}
5 5 x++
6 - ····}
7 6 }
8 7

function f(x) {
if (x < 0) {
return 0;
} else {
return x;
}
}
code-block.js:4:7 lint/style/noUselessElse  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This else clause can be omitted because previous branches break early.

2 │ if (x < 0) {
3 │ return 0;
> 4 │ } else {
^^^^^^
> 5 │ return x;
> 6 │ }
^
7 │ }
8 │

Unsafe fix: Omit the else clause.

2 2 if (x < 0) {
3 3 return 0;
4 - ····}·else·{
4+ ····}
5 5 return x;
6 - ····}
7 6 }
8 7

function f(x) {
if (x < 0) {
throw new RangeError();
} else {
return x;
}
}
code-block.js:4:7 lint/style/noUselessElse  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This else clause can be omitted because previous branches break early.

2 │ if (x < 0) {
3 │ throw new RangeError();
> 4 │ } else {
^^^^^^
> 5 │ return x;
> 6 │ }
^
7 │ }
8 │

Unsafe fix: Omit the else clause.

2 2 if (x < 0) {
3 3 throw new RangeError();
4 - ····}·else·{
4+ ····}
5 5 return x;
6 - ····}
7 6 }
8 7

¥Valid

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");
}
}

¥Related links