noUselessElse
Este conteúdo não está disponível em sua língua ainda.
Summary
Section titled “Summary”- Rule available since:
v1.3.0 - Diagnostic Category:
lint/style/noUselessElse - This rule has a safe fix.
- The default severity of this rule is information.
- Sources:
- Inspired from
no-else-return - Inspired from
redundant_else
- Inspired from
How to configure
Section titled “How to configure”{ "linter": { "rules": { "style": { "noUselessElse": "error" } } }}Description
Section titled “Description”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 “Examples”Invalid
Section titled “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 │
ℹ 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 can be omitted because previous branches break early.
2 │ if (x < 0) {
3 │ return 0;
> 4 │ } else {
│ ^^^^^^
> 5 │ return x;
> 6 │ }
│ ^
7 │ }
8 │
ℹ 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 can be omitted because previous branches break early.
2 │ if (x < 0) {
3 │ throw new RangeError();
> 4 │ } else {
│ ^^^^^^
> 5 │ return x;
> 6 │ }
│ ^
7 │ }
8 │
ℹ 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"); }}Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.