Back to Biomejs

noDuplicateElseIf

src/content/docs/linter/rules/no-duplicate-else-if.mdx

latest2.9 KB
Original Source

import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.6.2` - Diagnostic Category: [`lint/suspicious/noDuplicateElseIf`](/reference/diagnostics#diagnostic-category) - This rule is **recommended**, meaning it is enabled by default. - This rule doesn't have a fix. - The default severity of this rule is [**error**](/reference/diagnostics#error). - Sources: - Same as [`no-dupe-else-if`](https://eslint.org/docs/latest/rules/no-dupe-else-if)

How to configure

json
{
	"linter": {
		"rules": {
			"suspicious": {
				"noDuplicateElseIf": "error"
			}
		}
	}
}

Description

Disallow duplicate conditions in if-else-if chains

if-else-if chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions.

Two identical test conditions in the same chain are almost always a mistake in the code. Unless there are side effects in the expressions, a duplicate will evaluate to the same true or false value as the identical expression earlier in the chain, meaning that its branch can never execute.

Please note that this rule does not compare conditions from the chain with conditions inside statements

Examples

Invalid

js
if (a) {
    foo();
} else if (b) {
    bar();
} else if (b) {
    baz();
}
<pre class="language-text"><code class="language-text">code-block.js:5:12 <a href="https://biomejs.dev/linter/rules/no-duplicate-else-if">lint/suspicious/noDuplicateElseIf</a> ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ <strong><span style="color: Tomato;">✖</span></strong> <span style="color: Tomato;">This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain.</span> <strong>3 │ </strong>&#125; else if (b) &#123; <strong>4 │ </strong> bar(); <strong><span style="color: Tomato;">&gt;</span></strong> <strong>5 │ </strong>&#125; else if (b) &#123; <strong> │ </strong> <strong><span style="color: Tomato;">^</span></strong> <strong>6 │ </strong> baz(); <strong>7 │ </strong>&#125; </code></pre>

Valid

js
if (a) {
    foo();
} else if (b) {
    bar();
} else if (c) {
    baz();
}
</TabItem> </Tabs>