]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/src/rules/no-constant-condition.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / no-constant-condition.md
CommitLineData
8f9d1d4d
DC
1---
2title: no-constant-condition
8f9d1d4d
DC
3rule_type: problem
4related_rules:
5- no-constant-binary-expression
6---
7
8
eb39fafa
DC
9
10A 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.
11
12```js
13if (false) {
14 doSomethingUnfinished();
15}
16```
17
18## Rule Details
19
20This rule disallows constant expressions in the test condition of:
21
22* `if`, `for`, `while`, or `do...while` statement
23* `?:` ternary expression
24
25Examples of **incorrect** code for this rule:
26
8f9d1d4d
DC
27::: incorrect
28
eb39fafa
DC
29```js
30/*eslint no-constant-condition: "error"*/
31
32if (false) {
33 doSomethingUnfinished();
34}
35
36if (void x) {
37 doSomethingUnfinished();
38}
39
456be15e
TL
40if (x &&= false) {
41 doSomethingNever();
42}
43
34eeec05
TL
44if (class {}) {
45 doSomethingAlways();
46}
47
48if (new Boolean(x)) {
49 doSomethingAlways();
50}
51
8f9d1d4d
DC
52if (Boolean(1)) {
53 doSomethingAlways();
54}
55
56if (undefined) {
57 doSomethingUnfinished();
58}
59
456be15e
TL
60if (x ||= true) {
61 doSomethingAlways();
62}
63
eb39fafa
DC
64for (;-2;) {
65 doSomethingForever();
66}
67
68while (typeof x) {
69 doSomethingForever();
70}
71
72do {
73 doSomethingForever();
74} while (x = -1);
75
76var result = 0 ? a : b;
f2a92ac6
DC
77
78if(input === "hello" || "bye"){
79 output(input);
80}
eb39fafa
DC
81```
82
8f9d1d4d
DC
83:::
84
eb39fafa
DC
85Examples of **correct** code for this rule:
86
8f9d1d4d
DC
87::: correct
88
eb39fafa
DC
89```js
90/*eslint no-constant-condition: "error"*/
91
92if (x === 0) {
93 doSomething();
94}
95
96for (;;) {
97 doSomethingForever();
98}
99
100while (typeof x === "undefined") {
101 doSomething();
102}
103
104do {
105 doSomething();
106} while (x);
107
108var result = x !== 0 ? a : b;
f2a92ac6
DC
109
110if(input === "hello" || input === "bye"){
111 output(input);
112}
eb39fafa
DC
113```
114
8f9d1d4d
DC
115:::
116
eb39fafa
DC
117## Options
118
119### checkLoops
120
121Set to `true` by default. Setting this option to `false` allows constant expressions in loops.
122
123Examples of **correct** code for when `checkLoops` is `false`:
124
8f9d1d4d
DC
125::: correct
126
eb39fafa
DC
127```js
128/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
129
130while (true) {
131 doSomething();
132 if (condition()) {
133 break;
134 }
135};
136
137for (;true;) {
138 doSomething();
139 if (condition()) {
140 break;
141 }
142};
143
144do {
145 doSomething();
146 if (condition()) {
147 break;
148 }
149} while (true)
150```
8f9d1d4d
DC
151
152:::