Skip to content

noUselessElse (JavaScript)

Language JavaScript (and super languages)
biome.json
{
"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++
}
}
code-block.js:4:7 lint/style/noUselessElse  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ This else clause is unnecessary.

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

ℹ The previous branches break early, so the code in the else clause only runs when none of them matched. The clause adds a level of nesting without changing behavior.

ℹ Safe 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 is unnecessary.

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

ℹ The previous branches break early, so the code in the else clause only runs when none of them matched. The clause adds a level of nesting without changing behavior.

ℹ Safe 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 is unnecessary.

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

ℹ The previous branches break early, so the code in the else clause only runs when none of them matched. The clause adds a level of nesting without changing behavior.

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