Using Null in JavaScript

When should the null type be used and avoided?

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.

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


// 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) {

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

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

Leave a Reply

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

You are commenting using your 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