跳转到内容

noUselessElse

此内容尚不支持你的语言。

Diagnostic Category: lint/style/noUselessElse

Since: v1.3.0

Sources:

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++
}
}
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

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