Check if a Variable is Not NULL in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

banner

Photo by Joseph Young

Check if a Variable is Not NULL in JavaScript #

Use the strict inequality (!==) operator to check if a variable is not null - 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 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.

This means that 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 runs.

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee