Skip to content

Instantly share code, notes, and snippets.

@anthonyalvarez
Last active October 23, 2018 21:05
Show Gist options
  • Select an option

  • Save anthonyalvarez/5b6107152f09b2d979fb7211bb1cf2dc to your computer and use it in GitHub Desktop.

Select an option

Save anthonyalvarez/5b6107152f09b2d979fb7211bb1cf2dc to your computer and use it in GitHub Desktop.
Avoid Null Comparisons

Avoid Null Comparisons

Comparison to null does not actually prevent errors. Comparing a variable against null typically does not provide enough information about the value to determine whether it's safe to proceed. Fortunately, JavaScript has a number of ways to determine the true calue of a variable.

Detecting Primative Values

There are 5 primitive types in JavaScript:

  1. string
  2. number
  3. boolean
  4. Null
  5. Undefined

The typeof operator is the best option to determine a value a primitive value. It returns a string indicating the type of value. It is not a function.

Basic Syntax

typeof <variable-name>

Using typeof for detecting four primitive value types is the safest way to code defensively.

// detect a string 
if (typeof name === 'string') {
  anotherName = name.substring(3);
}

// detect a number
if (typeof count === 'number') {
  updateCount(count);
}

// detect a boolean
if (typeof found === 'boolean'&& found) {
  message('Found!');
}

// detect undefined
if (typeof MyApp === 'undefined') {
  MyApp = {
    // code
    }
}

typeof operator is also unique in that it can be used on an undeclared variable without throwing an error. Both undeclared variables and variables whoes value is undefined return "undefined" when typeof is used.

The last primitive value, null, is the one you normally should not check for because typeof does not give enought information about whether the value was expected. There is one exception: if on of the expected values is actually null, then it is OK to test for it directly. But the comparison should be done using === pr !== against null.

// if you must test for null, this is the way to go
var element = document.getElementById ('my-div');
if (element !== null) {
  element.className = 'found';
 }

It is possible for document.getElementById () to return null if the given DOM element is not found. The method will return null or an element. Because null is one of the expected outcomes, it is OK to test for it using !==.

Detecting Reference Values

Also known as objects. In JavaScript any value that is not a primitive is a reference. There are several built-in reference types such as Object Array, Date and Error, just to name a few. typeof returns "object for any type of object as well and null and is not useful.

The instanceof is best for detecting values of a reference type.

Syntax

// detect a Date
 if (value instanceof Date) {
  console.log(value.getFullYear());
  }
  
// detect a RegExp
 if (value.test instanceof RegExp) {
  console.log('matches');
  }
  
// detect an Error
 if (value instanceof Error) {
  throw value;
  }

Detecting Functions

Functions are technically reference types in JavaScript. Using typeof is the best way to detect functions.

Syntax

function myFunc() {}

// Good
console.log(typeof myFunc === 'function');  // true 

Detecting Arrays

Douglas Crockford duck typing relies on the fact that arrays are the only objects with a sort() method but this approach yeild true for any other type of object with a sort() method too.

Syntax

// Duck Typing Arrays
function isArray(value) {
  return typeof value.sort === 'function';
  }

Detecting Properties

To determine whether a property is present in an object. The best way to detect the presense of a property is to use the in operator which checks for the prescense of the named property without reading its value.

Syntax

var object = {
  count: 0,
  related: null
};

// Good
if ('count' in object {
  // this executes
}

if ('related' in object {
  // this executes
}

To check for property existence on the object instace use hasOwnProperty() method.

Syntax

// Good for all non-DOM objects
if (object.hasOwnProperty('related')) {
  // this executes
}

// Good when your are not sure
if (hasOwnProperty in object && object.hasOwnProperty('related')) {
  // this executes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment