Using Null in JavaScript

Question
When should the null type be used and avoided?

Answer
Use null in the following scenarios:
-To initialize a variable that will later be assigned an object.
-To perform a comparison against a variable that may or may not be an object.
-To pass into a function where an object is expected.
-To return from a function where an object is expected.

Avoid null in the following cases:
-To test whether an argument is supplied.
-To test an uninitialized variable’s value for null.

Comments
A good way to think about null is as a placeholder for an object.

Examples

// Good.
// The variable will be assigned an object.
let account = null;

// Good.
// Returning when an object is expected.
function getAccount() {
  if (condition) {
    return new Account("Free Checking");
  } else {
    return null;
  }
}

// Good.
// Comparing against a variable that's an object.
let account = getAccount();
if (account !== null) {
  doWork();
}

// Bad.
// Comparing against an uninitialized variable.
let account;
if (account != null) {
  doWork();
}

// Bad.
// Checking whether an argument was passed in.
function doWork(argOne, argTwo) {
  if (argTwo != null) {
    doSomeOtherWork();
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s