Result of typeof should be compared with correct value

  • BAD_TYPEOF_COMPARISON
  • Error
  • Medium
  • No tags

This rule applies when the result of typeof is compared with incorrect value.

Possible return values of typeof operator are the following strings:

  • "undefined"
  • "object"
  • "boolean"
  • "number"
  • "string"
  • "symbol"
  • "function"

Therefore, if a programmer compares with the value not listed above, it will always result in false undesirably.

For more information, please see this documentation.

Noncompliant Code Example

// Example 1
// BAD_TYPEOF_COMPARISON alarm because 'array' is not the possible return value of typeof.
if (typeof x === 'array') { console.log('x is array'); }

// Example 2
// BAD_TYPEOF_COMPARISON alarm because 'udefined' is mistyping of 'undefined'.
var zkPort = typeof portValue === 'udefined' ? '2181' : portValue;

// Example 3
// BAD_TYPEOF_COMPARISON alarm because typeof result is not compared with a string value.
if (typeof x === undefined) { console.log('x is undefined'); }

// Example 4
// BAD_TYPEOF_COMPARISON alarm because typeof result is not compared with a string value.
if (typeof x) { console.log('x is not undefined'); }

Compliant Code Example

// Example 1
// Use Array.isArray().
if (Array.isArray(x)) { console.log('x is array'); }

// Use a function in third-party libraries like jQuery or underscore.
if ($.isArray(x)) { console.log('x is array'); }

// Example 2
var zkPort = typeof portValue === 'undefined' ? '2181' : portValue;

// Example 3
if (typeof x === 'undefined') { console.log('x is undefined'); }

// Example 4
if (typeof x !== 'undefined') { console.log('x is not undefined'); }

Version

This rule was introduced in DeepScan 1.0.0-alpha.

See