]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-constant-binary-expression.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / no-constant-binary-expression.md
1 ---
2 title: no-constant-binary-expression
3 layout: doc
4 rule_type: problem
5 related_rules:
6 - no-constant-condition
7 further_reading:
8 - https://eslint.org/blog/2022/07/interesting-bugs-caught-by-no-constant-binary-expression/
9 ---
10
11
12 Comparisons which will always evaluate to true or false and logical expressions (`||`, `&&`, `??`) which either always short-circuit or never short-circuit are both likely indications of programmer error.
13
14 These errors are especially common in complex expressions where operator precedence is easy to misjudge. For example:
15
16 ```js
17 // One might think this would evaluate as `a + (b ?? c)`:
18 const x = a + b ?? c;
19
20 // But it actually evaluates as `(a + b) ?? c`. Since `a + b` can never be null,
21 // the `?? c` has no effect.
22 ```
23
24 Additionally, this rule detects comparisons to newly constructed objects/arrays/functions/etc. In JavaScript, where objects are compared by reference, a newly constructed object can _never_ `===` any other value. This can be surprising for programmers coming from languages where objects are compared by value.
25
26 ```js
27 // Programmers coming from a language where objects are compared by value might expect this to work:
28 const isEmpty = x === [];
29
30 // However, this will always result in `isEmpty` being `false`.
31 ```
32
33 ## Rule Details
34
35 This rule identifies `==` and `===` comparisons which, based on the semantics of the JavaScript language, will always evaluate to `true` or `false`.
36
37 It also identifies `||`, `&&` and `??` logical expressions which will either always or never short-circuit.
38
39 Examples of **incorrect** code for this rule:
40
41 ::: incorrect
42
43 ```js
44 /*eslint no-constant-binary-expression: "error"*/
45
46 const value1 = +x == null;
47
48 const value2 = condition ? x : {} || DEFAULT;
49
50 const value3 = !foo == null;
51
52 const value4 = new Boolean(foo) === true;
53
54 const objIsEmpty = someObj === {};
55
56 const arrIsEmpty = someArr === [];
57 ```
58
59 :::
60
61 Examples of **correct** code for this rule:
62
63 ::: correct
64
65 ```js
66 /*eslint no-constant-binary-expression: "error"*/
67
68 const value1 = x == null;
69
70 const value2 = (condition ? x : {}) || DEFAULT;
71
72 const value3 = !(foo == null);
73
74 const value4 = Boolean(foo) === true;
75
76 const objIsEmpty = Object.keys(someObj).length === 0;
77
78 const arrIsEmpty = someArr.length === 0;
79 ```
80
81 :::