]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-constant-condition.md
8de5e69f3f8feb495c801ea5c7876fc5d48f8489
[pve-eslint.git] / eslint / docs / rules / no-constant-condition.md
1 # disallow constant expressions in conditions (no-constant-condition)
2
3 A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.
4
5 ```js
6 if (false) {
7 doSomethingUnfinished();
8 }
9 ```
10
11 ## Rule Details
12
13 This rule disallows constant expressions in the test condition of:
14
15 * `if`, `for`, `while`, or `do...while` statement
16 * `?:` ternary expression
17
18 Examples of **incorrect** code for this rule:
19
20 ```js
21 /*eslint no-constant-condition: "error"*/
22
23 if (false) {
24 doSomethingUnfinished();
25 }
26
27 if (void x) {
28 doSomethingUnfinished();
29 }
30
31 if (x &&= false) {
32 doSomethingNever();
33 }
34
35 if (class {}) {
36 doSomethingAlways();
37 }
38
39 if (new Boolean(x)) {
40 doSomethingAlways();
41 }
42
43 if (x ||= true) {
44 doSomethingAlways();
45 }
46
47 for (;-2;) {
48 doSomethingForever();
49 }
50
51 while (typeof x) {
52 doSomethingForever();
53 }
54
55 do {
56 doSomethingForever();
57 } while (x = -1);
58
59 var result = 0 ? a : b;
60 ```
61
62 Examples of **correct** code for this rule:
63
64 ```js
65 /*eslint no-constant-condition: "error"*/
66
67 if (x === 0) {
68 doSomething();
69 }
70
71 for (;;) {
72 doSomethingForever();
73 }
74
75 while (typeof x === "undefined") {
76 doSomething();
77 }
78
79 do {
80 doSomething();
81 } while (x);
82
83 var result = x !== 0 ? a : b;
84 ```
85
86 ## Options
87
88 ### checkLoops
89
90 Set to `true` by default. Setting this option to `false` allows constant expressions in loops.
91
92 Examples of **correct** code for when `checkLoops` is `false`:
93
94 ```js
95 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
96
97 while (true) {
98 doSomething();
99 if (condition()) {
100 break;
101 }
102 };
103
104 for (;true;) {
105 doSomething();
106 if (condition()) {
107 break;
108 }
109 };
110
111 do {
112 doSomething();
113 if (condition()) {
114 break;
115 }
116 } while (true)
117 ```