![github-actions[bot]](/assets/img/avatar_default.png)
You can preview this rule [here](https://sonarsource.github.io/rspec/#/rspec/S6836/javascript) (updated a few minutes after each push). ## Review A dedicated reviewer checked the rule description successfully for: - [ ] logical errors and incorrect information - [ ] information gaps and missing content - [ ] text style and tone - [ ] PR summary and labels follow [the guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule) --------- Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com> Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com> Co-authored-by: Yassin Kammoun <52890329+yassin-kammoun-sonarsource@users.noreply.github.com> Co-authored-by: Ilia Kebets <104737176+ilia-kebets-sonarsource@users.noreply.github.com>
51 lines
1.4 KiB
Plaintext
51 lines
1.4 KiB
Plaintext
== 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]
|