]> git.proxmox.com Git - pve-eslint.git/blame - 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
CommitLineData
8f9d1d4d
DC
1---
2title: no-extra-boolean-cast
8f9d1d4d
DC
3rule_type: suggestion
4---
5
6
7
8
eb39fafa
DC
9
10In 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
13if (!!foo) {
14 // ...
15}
16
17if (Boolean(foo)) {
18 // ...
19}
20
21if (foo) {
22 // ...
23}
24```
25
26## Rule Details
27
28This rule disallows unnecessary boolean casts.
29
30Examples of **incorrect** code for this rule:
31
8f9d1d4d
DC
32::: incorrect
33
eb39fafa
DC
34```js
35/*eslint no-extra-boolean-cast: "error"*/
36
37var foo = !!!bar;
38
39var foo = !!bar ? baz : bat;
40
41var foo = Boolean(!!bar);
42
43var foo = new Boolean(!!bar);
44
45if (!!foo) {
46 // ...
47}
48
49if (Boolean(foo)) {
50 // ...
51}
52
53while (!!foo) {
54 // ...
55}
56
57do {
58 // ...
59} while (Boolean(foo));
60
61for (; !!foo; ) {
62 // ...
63}
64```
65
8f9d1d4d
DC
66:::
67
eb39fafa
DC
68Examples of **correct** code for this rule:
69
8f9d1d4d
DC
70::: correct
71
eb39fafa
DC
72```js
73/*eslint no-extra-boolean-cast: "error"*/
74
75var foo = !!bar;
76var foo = Boolean(bar);
77
78function foo() {
79 return !!bar;
80}
81
82var foo = bar ? !!baz : !!bat;
83```
84
8f9d1d4d
DC
85:::
86
eb39fafa
DC
87## Options
88
89This 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
95Examples of **incorrect** code for this rule with `"enforceForLogicalOperands"` option set to `true`:
96
8f9d1d4d
DC
97::: incorrect
98
eb39fafa
DC
99```js
100/*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]*/
101
102if (!!foo || bar) {
103 //...
104}
105
106while (!!foo && bar) {
107 //...
108}
109
110if ((!!foo || bar) && baz) {
111 //...
112}
113
114foo && Boolean(bar) ? baz : bat
115
116var foo = new Boolean(!!bar || baz)
117```
118
8f9d1d4d
DC
119:::
120
eb39fafa
DC
121Examples of **correct** code for this rule with `"enforceForLogicalOperands"` option set to `true`:
122
8f9d1d4d
DC
123::: correct
124
eb39fafa
DC
125```js
126/*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]*/
127
128if (foo || bar) {
129 //...
130}
131
132while (foo && bar) {
133 //...
134}
135
136if ((foo || bar) && baz) {
137 //...
138}
139
140foo && bar ? baz : bat
141
142var foo = new Boolean(bar || baz)
143
144var foo = !!bar || baz;
145```
8f9d1d4d
DC
146
147:::