Bitwise operators should not be used where logical operators are expected

  • BAD_BITWISE_OPERATOR
  • Error
  • High, Medium
  • cwe

This rule applies when bitwise operators are used where logical operators are expected.

Bitwise operators have different results from logical operators and a TypeError exception may be thrown because short-circuit evaluation is not applied. (In short-circuit evaluation, right operand evaluation is skipped according to left operand value, e.g. x is false in x && y.)

It is obvious that logical operators are expected in the following code patterns:

  1. e && e.x
  2. e || {}
  3. e || ''

Noncompliant Code Example

View with compliant examples side by side
// Example 1
var obj = null;
if (obj & obj.prop) { // BAD_BITWISE_OPERATOR alarm
    console.log(obj.prop);
}

// Example 2
options = options | {}; // BAD_BITWISE_OPERATOR alarm

// Example 3
input |= ''; // BAD_BITWISE_OPERATOR alarm

Compliant Code Example

View with noncompliant examples side by side
// Example 1
var obj = null;
if (obj && obj.prop) {
    console.log(obj.prop);
}

// Example 2
options = options || {};

// Example 3
input = input || '';

Version

This rule was introduced in DeepScan 1.0.0-alpha.

See