null or undefined check should be consistent for all accesses of a variable

  • INSUFFICIENT_NULL_CHECK
  • Error
  • Medium
  • No tags

This rule applies when a variable is checked for null (or undefined) value at one point but is accessed without null check at another point.

If the variable has indeed null value, TypeError exception occurs when trying to access its property or call it as a function.

Therefore, a programmer needs to check the following:

  • Access a variable consistently after checking it is not null
  • Remove all null checks of a variable consistently if it cannot be null

Noncompliant Code Example

// Example 1
function foo(x) {
    x.p = 42;
    if (x != null) { // INSUFFICIENT_NULL_CHECK alarm
    }
}

// Example 2
function foo(x) {
    if (x != null) { // INSUFFICIENT_NULL_CHECK alarm
    }
    y = x.p;
}

// Example 3
function foo(cb) {
    cb();
    if (cb != null) { // INSUFFICIENT_NULL_CHECK alarm
    }
}

Compliant Code Example

// Example 1
function foo(x) {
    if (x != null) {
        x.p = 42;
    }
}

// Example 2
function foo(x) {
    if (x != null) {
    }
    y = x ? x.p : '';
}

// Example 3
function foo(cb) {
    if (cb != null) {
        cb();
    }
}

Version

This rule was introduced in DeepScan 1.0.0-alpha.