src/content/docs/linter/rules/no-switch-declarations.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.0.0` - Diagnostic Category: [`lint/correctness/noSwitchDeclarations`](/reference/diagnostics#diagnostic-category) - This rule is **recommended**, meaning it is enabled by default. - This rule has a [**safe**](/linter/#safe-fixes) fix. - The default severity of this rule is [**error**](/reference/diagnostics#error). - Sources: - Same as [`no-case-declarations`](https://eslint.org/docs/latest/rules/no-case-declarations){
"linter": {
"rules": {
"correctness": {
"noSwitchDeclarations": "error"
}
}
}
}
Disallow lexical declarations in switch clauses.
Lexical declarations in switch clauses are accessible in the entire switch.
However, it only gets initialized when it is assigned, which will only happen if the switch clause where it is defined is reached.
To ensure that the lexical declarations only apply to the current switch clause wrap your declarations in a block.
switch (foo) {
case 0:
const x = 1;
break;
case 2:
x; // `x` can be used while it is not initialized
break;
}
switch (foo) {
case 0:
function f() {}
break;
case 2:
f(); // `f` can be called here
break;
}
switch (foo) {
case 0:
class A {}
break;
default:
new A(); // `A` can be instantiated here
break;
}
switch (foo) {
case 0: {
const x = 1;
break;
}
case 1:
// `x` is not visible here
break;
}