]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/default-case.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / default-case.md
1 ---
2 title: default-case
3 layout: doc
4 rule_type: suggestion
5 related_rules:
6 - no-fallthrough
7 ---
8
9
10 Some code conventions require that all `switch` statements have a `default` case, even if the default case is empty, such as:
11
12 ```js
13 switch (foo) {
14 case 1:
15 doSomething();
16 break;
17
18 case 2:
19 doSomething();
20 break;
21
22 default:
23 // do nothing
24 }
25 ```
26
27 The thinking is that it's better to always explicitly state what the default behavior should be so that it's clear whether or not the developer forgot to include the default behavior by mistake.
28
29 Other code conventions allow you to skip the `default` case so long as there is a comment indicating the omission is intentional, such as:
30
31 ```js
32 switch (foo) {
33 case 1:
34 doSomething();
35 break;
36
37 case 2:
38 doSomething();
39 break;
40
41 // no default
42 }
43 ```
44
45 Once again, the intent here is to show that the developer intended for there to be no default behavior.
46
47 ## Rule Details
48
49 This rule aims to require `default` case in `switch` statements. You may optionally include a `// no default` after the last `case` if there is no `default` case. The comment may be in any desired case, such as `// No Default`.
50
51 Examples of **incorrect** code for this rule:
52
53 ::: incorrect
54
55 ```js
56 /*eslint default-case: "error"*/
57
58 switch (a) {
59 case 1:
60 /* code */
61 break;
62 }
63
64 ```
65
66 :::
67
68 Examples of **correct** code for this rule:
69
70 ::: correct
71
72 ```js
73 /*eslint default-case: "error"*/
74
75 switch (a) {
76 case 1:
77 /* code */
78 break;
79
80 default:
81 /* code */
82 break;
83 }
84
85 switch (a) {
86 case 1:
87 /* code */
88 break;
89
90 // no default
91 }
92
93 switch (a) {
94 case 1:
95 /* code */
96 break;
97
98 // No Default
99 }
100 ```
101
102 :::
103
104 ## Options
105
106 This rule accepts a single options argument:
107
108 * Set the `commentPattern` option to a regular expression string to change the default `/^no default$/i` comment test pattern
109
110 ### commentPattern
111
112 Examples of **correct** code for the `{ "commentPattern": "^skip\\sdefault" }` option:
113
114 ::: correct
115
116 ```js
117 /*eslint default-case: ["error", { "commentPattern": "^skip\\sdefault" }]*/
118
119 switch(a) {
120 case 1:
121 /* code */
122 break;
123
124 // skip default
125 }
126
127 switch(a) {
128 case 1:
129 /* code */
130 break;
131
132 // skip default case
133 }
134 ```
135
136 :::
137
138 ## When Not To Use It
139
140 If you don't want to enforce a `default` case for `switch` statements, you can safely disable this rule.