The logical negation operator should be used in correct order

  • BAD_NEGATION_OPERATOR
  • Error
  • Medium
  • cwe

This rule applies when the logical negation operator (!) is evaluated in incorrect order because of operator precedence.

For example, if code to test whether x is not array is written like !x instanceof Array, it is evaluated as (!x) instanceof Array, resulting in false regardless of x. In this case, explicit parentheses should be used as in !(x instanceof Array) because ! has higher precedence than binary operators.

The following binary operators are considered: in, instanceof, <, >, <=, >=, ==, !=, ===, !==

Noncompliant Code Example

View with compliant examples side by side
// Example 1
if (!x instanceof Array) { // BAD_NEGATION_OPERATOR alarm. The result is always false.
    console.log('x is not array');
}

// Example 2
if (!x.length === 0) { // BAD_NEGATION_OPERATOR alarm. The result is always false.
    console.log('x is not empty');
}

Compliant Code Example

View with noncompliant examples side by side
// Example 1
if (!(x instanceof Array)) {
    console.log('x is not array');
}

// Example 2
if (x.length !== 0) {
    console.log('x is not empty');
}

Version

This rule was introduced in DeepScan 1.0.0-alpha.

See

Was this documentation helpful?