Object literal should not be used for comparison

  • BAD_OBJECT_LITERAL_COMPARISON
  • Error
  • Medium
  • No tags

This rule applies when an object literal is used for comparison.

Fresh object is allocated at Object or Array literal, so the following comparison with the literal has always the same result and can lead to unintended behavior.

  1. Strict equality comparison(===, !==) of the literal with any type
  2. Equality comparison(==, !=) of the literal with an object type

Noncompliant Code Example

View with compliant examples side by side
// Example 1
if (x === {}) { // BAD_OBJECT_LITERAL_COMPARISON alarm because of strict equality comparison with an object literal.
    console.log('x is an empty object');
} else if (x === []) { // BAD_OBJECT_LITERAL_COMPARISON alarm because of strict equality comparison with an array literal.
    console.log('x is an empty array');
}

// Example 2
var obj = {};
if (obj === {}) { // BAD_OBJECT_LITERAL_COMPARISON alarm because of equality comparison of an object literal with an object type.
    console.log('obj is an empty object');
}

Compliant Code Example

View with noncompliant examples side by side
// Example 1
if (Array.isArray(x)) {
    // Empty checking for an array
    if (x.length === 0) {
        console.log('x is an empty array');
    }
} else if (typeof x === 'object') {
    // Empty checking for an object
    if (Object.keys(x).length === 0) {
        console.log('x is an empty object');
    }
}

// Example 2
var obj = {};
if (typeof obj === 'object' && Object.keys(obj).length === 0) {
    console.log('obj is an empty object');
}

Version

This rule was introduced in DeepScan 1.12.0-beta.

See