noUselessElse
このコンテンツはまだ日本語訳がありません。
Diagnostic Category: lint/style/noUselessElse
Since: v1.3.0
Sources:
- Inspired from:
no-else-return
- Inspired from:
redundant_else
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.
Examples
Section titled ExamplesInvalid
Section titled Invalidcode-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 │
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 │
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 │