Skip to content

eslint/no-unsafe-negation Correctness

This rule is turned on by default.
🛠️ An auto-fix is available for this rule.

What it does

Disallows negating the left operand of relational operators to prevent logical errors caused by misunderstanding operator precedence or accidental use of negation.

Why is this bad?

Negating the left operand of relational operators can result in unexpected behavior due to operator precedence, leading to logical errors. For instance, !a in b may be interpreted as (!a) in b instead of !(a in b), which is not the intended logic.

Examples

Examples of incorrect code for this rule:

javascript
if ((!key) in object) {
}

if ((!obj) instanceof Ctor) {
}

Examples of correct code for this rule:

javascript
if (!(key in object)) {
}

if (!(obj instanceof Ctor)) {
}

Options

enforceForOrderingRelations

{ type: boolean, default: false }

The enforceForOrderingRelations option determines whether negation is allowed on the left-hand side of ordering relational operators (<, >, <=, >=).

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).

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny no-unsafe-negation
json
{
  "rules": {
    "no-unsafe-negation": "error"
  }
}

References

Released under the MIT License.