Check if a Variable is Not NULL in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a Variable is Not NULL in JavaScript #

Use the strict inequality (!==) operator to check if a variable is not null, e.g. myVar !== null. The strict inequality operator will return true if the variable is not equal to null and false otherwise.

index.js
const a = 'hello'; if (a !== null) { console.log('✅ a is NOT null'); } else { console.log('⛔️ a is null'); }

We used the strict inequality (!==) operator to check if the value stored in the variable a is not equal to null.

The operator returns a boolean result:

  • true if the values are not equal
  • false if the values are equal
index.js
console.log(null !== null); // 👉️ false console.log('hello' !== null); // 👉️ true

The strict inequality (!==) operator considers two values of different types to be different, as opposed to the loose inequality (!=) operator.

This means that if you compare null with any other type, the strict inequality (!==) operator will always return false.

A very common mistake is to check if a value is truthy, instead of checking if it's not null. Here's an example.
index.js
const a = 'hello'; if (a) { console.log(`🚨 a is NOT false, 0, empty string, null, undefined, NaN`); } else { console.log(`⛔️️ a is ONE OF false, 0, empty string, null, undefined, NaN`); }

In this example, we check if the value stored in the variable a is truthy. Truthy are all values that are not falsy.

The falsy values in JavaScript are: false, 0, "", null, undefined, NaN.

If the else block runs, the value of a is falsy and could be either of the 6 falsy values, not necessarily null.

Things could go wrong in so many different ways when doing this. For example, if the value of a is equal to 0, the else block would run.

index.js
const a = 0; if (a) { console.log("⛔️ This doesn't run"); } else { console.log('✅ This runs'); }

Even if this is what you want, you should never write code like this because it's confusing and indirect.

Instead, you should be more explicit:

index.js
const a = 0; if (a === 0) { console.log('✅ This runs'); } else { console.log("⛔️ This doesn't run"); }
It's always recommended to explicitly use the strict operators (!==, ===) when making equality comparisons. They make your code more readable, explicit and less prone to errors.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.