Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

disallow negating the left operand of relational operators (no-unsafe-negation) #595

Closed
feross opened this issue Aug 19, 2016 · 0 comments
Closed

Comments

@feross
Copy link
Member

feross commented Aug 19, 2016

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.

Rule Details

This rule disallows negating the left operand of Relational Operators.

Relational Operators are:

  • in operator.
  • instanceof operator.

Examples of incorrect code for this rule:

/*eslint no-unsafe-negation: "error"*/

if (!key in object) {
    // operator precedence makes it equivalent to (!key) in object
    // and type conversion makes it equivalent to (key ? "false" : "true") in object
}

if (!obj instanceof Ctor) {
    // operator precedence makes it equivalent to (!obj) instanceof Ctor
    // and it equivalent to always false since boolean values are not objects.
}

Examples of correct code for this rule:

/*eslint no-unsafe-negation: "error"*/

if (!(key in object)) {
    // key is not in object
}

if (!(obj instanceof Ctor)) {
    // obj is not an instance of Ctor
}

if(("" + !key) in object) {
    // make operator precedence and type conversion explicit
    // in a rare situation when that is the intended meaning
}

http://eslint.org/docs/rules/no-unsafe-negation

Likely to catch bugs, and there's basically never a reason to write code that this would flag, so I'll merge this into the standard v8 beta.

@feross feross modified the milestone: v8 Aug 19, 2016
feross added a commit to standard/eslint-config-standard that referenced this issue Aug 19, 2016
@feross feross closed this as completed Aug 19, 2016
@lock lock bot locked as resolved and limited conversation to collaborators May 10, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
Archived in project
Development

No branches or pull requests

1 participant