51 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
The ECMAScript specification allows for creating block-level lexical declarations (`let`, `const`, `function`, and `class`) in any block statement or expression. However, when these declarations are made inside the `case` or `default` clause of a `switch` statement, they are not confined to the block of that `case` or `default` clause. Instead, they apply to the whole `switch` block but only get initialized when the cases are reached, which can lead to unexpected behavior.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
switch (foo) {
case 1:
let x = 1; // Noncompliant
break;
case 2:
const y = 2; // Noncompliant
break;
case 3:
function f() {} // Noncompliant
break;
case 4:
class C {} // Noncompliant
break;
}
----
To fix this, you can create a nested block within each `case` or `default` clause, ensuring each declaration is properly scoped to its respective block.
[source,javascript,diff-id=1,diff-type=compliant]
----
switch (foo) {
case 1: {
let x = 1;
break;
}
case 2: {
const y = 2;
break;
}
case 3: {
function f() {}
break;
}
case 4: {
class C {}
break;
}
}
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch[switch]