]>
Commit | Line | Data |
---|---|---|
8f9d1d4d DC |
1 | --- |
2 | title: no-eq-null | |
8f9d1d4d DC |
3 | rule_type: suggestion |
4 | --- | |
5 | ||
eb39fafa DC |
6 | |
7 | Comparing to `null` without a type-checking operator (`==` or `!=`), can have unintended results as the comparison will evaluate to true when comparing to not just a `null`, but also an `undefined` value. | |
8 | ||
9 | ```js | |
10 | if (foo == null) { | |
11 | bar(); | |
12 | } | |
13 | ``` | |
14 | ||
15 | ## Rule Details | |
16 | ||
17 | The `no-eq-null` rule aims reduce potential bug and unwanted behavior by ensuring that comparisons to `null` only match `null`, and not also `undefined`. As such it will flag comparisons to null when using `==` and `!=`. | |
18 | ||
19 | Examples of **incorrect** code for this rule: | |
20 | ||
8f9d1d4d DC |
21 | ::: incorrect |
22 | ||
eb39fafa DC |
23 | ```js |
24 | /*eslint no-eq-null: "error"*/ | |
25 | ||
26 | if (foo == null) { | |
27 | bar(); | |
28 | } | |
29 | ||
30 | while (qux != null) { | |
31 | baz(); | |
32 | } | |
33 | ``` | |
34 | ||
8f9d1d4d DC |
35 | ::: |
36 | ||
eb39fafa DC |
37 | Examples of **correct** code for this rule: |
38 | ||
8f9d1d4d DC |
39 | ::: correct |
40 | ||
eb39fafa DC |
41 | ```js |
42 | /*eslint no-eq-null: "error"*/ | |
43 | ||
44 | if (foo === null) { | |
45 | bar(); | |
46 | } | |
47 | ||
48 | while (qux !== null) { | |
49 | baz(); | |
50 | } | |
51 | ``` | |
609c276f | 52 | |
8f9d1d4d | 53 | ::: |
609c276f TL |
54 | |
55 | ## When Not To Use It | |
56 | ||
57 | If you want to enforce type-checking operations in general, use the more powerful [eqeqeq](./eqeqeq) instead. | |
8f9d1d4d DC |
58 | |
59 | ## Compatibility | |
60 | ||
61 | * **JSHint**: This rule corresponds to `eqnull` rule of JSHint. |