1 # disallow negating the left operand of relational operators (no-unsafe-negation)
3 Just as developers might type `-a + b` when they mean `-(a + b)` for the negative of a sum, they might type `!key in object` by mistake when they almost certainly mean `!(key in object)` to test that a key is not in an object. `!obj instanceof Ctor` is similar.
7 This rule disallows negating the left operand of the following relational operators:
9 - [`in` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in).
10 - [`instanceof` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof).
12 Examples of **incorrect** code for this rule:
15 /*eslint no-unsafe-negation: "error"*/
18 // operator precedence makes it equivalent to (!key) in object
19 // and type conversion makes it equivalent to (key ? "false" : "true") in object
22 if (!obj instanceof Ctor) {
23 // operator precedence makes it equivalent to (!obj) instanceof Ctor
24 // and it equivalent to always false since boolean values are not objects.
28 Examples of **correct** code for this rule:
31 /*eslint no-unsafe-negation: "error"*/
33 if (!(key in object)) {
34 // key is not in object
37 if (!(obj instanceof Ctor)) {
38 // obj is not an instance of Ctor
44 For rare situations when negating the left operand is intended, this rule allows an exception.
45 If the whole negation is explicitly wrapped in parentheses, the rule will not report a problem.
47 Examples of **correct** code for this rule:
50 /*eslint no-unsafe-negation: "error"*/
52 if ((!foo) in object) {
53 // allowed, because the negation is explicitly wrapped in parentheses
54 // it is equivalent to (foo ? "false" : "true") in object
55 // this is allowed as an exception for rare situations when that is the intended meaning
58 if(("" + !foo) in object) {
59 // you can also make the intention more explicit, with type conversion
63 Examples of **incorrect** code for this rule:
66 /*eslint no-unsafe-negation: "error"*/
68 if (!(foo) in object) {
69 // this is not an allowed exception
75 This rule has an object option:
77 - `"enforceForOrderingRelations": false` (default) allows negation of the left-hand side of ordering relational operators (`<`, `>`, `<=`, `>=`)
78 - `"enforceForOrderingRelations": true` disallows negation of the left-hand side of ordering relational operators
80 ### enforceForOrderingRelations
82 With this option set to `true` the rule is additionally enforced for:
89 The purpose is to avoid expressions such as `! a < b` (which is equivalent to `(a ? 0 : 1) < b`) when what is really intended is `!(a < b)`.
91 Examples of additional **incorrect** code for this rule with the `{ "enforceForOrderingRelations": true }` option:
94 /*eslint no-unsafe-negation: ["error", { "enforceForOrderingRelations": true }]*/
105 ## When Not To Use It
107 If you don't want to notify unsafe logical negations, then it's safe to disable this rule.