]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-extra-boolean-cast.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / no-extra-boolean-cast.md
1 ---
2 title: no-extra-boolean-cast
3 rule_type: suggestion
4 ---
5
6
7
8
9
10 In contexts such as an `if` statement's test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (`!!`) or a `Boolean` call is unnecessary. For example, these `if` statements are equivalent:
11
12 ```js
13 if (!!foo) {
14 // ...
15 }
16
17 if (Boolean(foo)) {
18 // ...
19 }
20
21 if (foo) {
22 // ...
23 }
24 ```
25
26 ## Rule Details
27
28 This rule disallows unnecessary boolean casts.
29
30 Examples of **incorrect** code for this rule:
31
32 ::: incorrect
33
34 ```js
35 /*eslint no-extra-boolean-cast: "error"*/
36
37 var foo = !!!bar;
38
39 var foo = !!bar ? baz : bat;
40
41 var foo = Boolean(!!bar);
42
43 var foo = new Boolean(!!bar);
44
45 if (!!foo) {
46 // ...
47 }
48
49 if (Boolean(foo)) {
50 // ...
51 }
52
53 while (!!foo) {
54 // ...
55 }
56
57 do {
58 // ...
59 } while (Boolean(foo));
60
61 for (; !!foo; ) {
62 // ...
63 }
64 ```
65
66 :::
67
68 Examples of **correct** code for this rule:
69
70 ::: correct
71
72 ```js
73 /*eslint no-extra-boolean-cast: "error"*/
74
75 var foo = !!bar;
76 var foo = Boolean(bar);
77
78 function foo() {
79 return !!bar;
80 }
81
82 var foo = bar ? !!baz : !!bat;
83 ```
84
85 :::
86
87 ## Options
88
89 This rule has an object option:
90
91 * `"enforceForLogicalOperands"` when set to `true`, in addition to checking default contexts, checks whether the extra boolean cast is contained within a logical expression. Default is `false`, meaning that this rule by default does not warn about extra booleans cast inside logical expression.
92
93 ### enforceForLogicalOperands
94
95 Examples of **incorrect** code for this rule with `"enforceForLogicalOperands"` option set to `true`:
96
97 ::: incorrect
98
99 ```js
100 /*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]*/
101
102 if (!!foo || bar) {
103 //...
104 }
105
106 while (!!foo && bar) {
107 //...
108 }
109
110 if ((!!foo || bar) && baz) {
111 //...
112 }
113
114 foo && Boolean(bar) ? baz : bat
115
116 var foo = new Boolean(!!bar || baz)
117 ```
118
119 :::
120
121 Examples of **correct** code for this rule with `"enforceForLogicalOperands"` option set to `true`:
122
123 ::: correct
124
125 ```js
126 /*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]*/
127
128 if (foo || bar) {
129 //...
130 }
131
132 while (foo && bar) {
133 //...
134 }
135
136 if ((foo || bar) && baz) {
137 //...
138 }
139
140 foo && bar ? baz : bat
141
142 var foo = new Boolean(bar || baz)
143
144 var foo = !!bar || baz;
145 ```
146
147 :::