]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-case-declarations.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / no-case-declarations.md
1 ---
2 title: no-case-declarations
3 rule_type: suggestion
4 related_rules:
5 - no-fallthrough
6 ---
7
8
9
10 This rule disallows lexical declarations (`let`, `const`, `function` and `class`)
11 in `case`/`default` clauses. The reason is that the lexical declaration is visible
12 in the entire switch block but it only gets initialized when it is assigned, which
13 will only happen if the case where it is defined is reached.
14
15 To ensure that the lexical declaration only applies to the current case clause
16 wrap your clauses in blocks.
17
18 ## Rule Details
19
20 This rule aims to prevent access to uninitialized lexical bindings as well as accessing hoisted functions across case clauses.
21
22 Examples of **incorrect** code for this rule:
23
24 ::: incorrect
25
26 ```js
27 /*eslint no-case-declarations: "error"*/
28 /*eslint-env es6*/
29
30 switch (foo) {
31 case 1:
32 let x = 1;
33 break;
34 case 2:
35 const y = 2;
36 break;
37 case 3:
38 function f() {}
39 break;
40 default:
41 class C {}
42 }
43 ```
44
45 :::
46
47 Examples of **correct** code for this rule:
48
49 ::: correct
50
51 ```js
52 /*eslint no-case-declarations: "error"*/
53 /*eslint-env es6*/
54
55 // Declarations outside switch-statements are valid
56 const a = 0;
57
58 switch (foo) {
59 // The following case clauses are wrapped into blocks using brackets
60 case 1: {
61 let x = 1;
62 break;
63 }
64 case 2: {
65 const y = 2;
66 break;
67 }
68 case 3: {
69 function f() {}
70 break;
71 }
72 case 4:
73 // Declarations using var without brackets are valid due to function-scope hoisting
74 var z = 4;
75 break;
76 default: {
77 class C {}
78 }
79 }
80 ```
81
82 :::
83
84 ## When Not To Use It
85
86 If you depend on fall through behavior and want access to bindings introduced in the case block.