Check if Variable is Null or Undefined in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

Check if Variable is NULL or Undefined #

To check if a variable is null or undefined use the || (or) operator to check if either of the two conditions is met. When used with two boolean values the || operator returns true if either of the conditions evaluate to true.

index.js
const age = null; // ๐Ÿ‘‡๏ธ Check if undefined or null if (age === undefined || age === null) { console.log('โœ… variable is undefined or null'); } else { console.log('โ›”๏ธ variable is NOT undefined or null'); } // ๐Ÿ‘‡๏ธ Check if NOT undefined or null if (age !== undefined && age !== null) { console.log('โœ… variable is NOT undefined or null'); }

Our first if statement checks if the age variable is either undefined or null.

If either of the conditions is satisfied the if block runs, otherwise the else block runs.

Our second if statement checks if the variable is NOT equal to null and is not equal to undefined.

For this example we use the logical && (and) operator to specify that both conditions have to be met for the if block to run.

For all of the examples above we used strict equality ===, however there is a more concise way to check if a variable is equal to null or undefined, using loose equality ==.

To check if a variable is equal to null or undefined, use the loose equality (==) operator. For example, age == null returns true if the variable age is null or undefined. Comparing null with undefined using the loose equality operator returns true.

index.js
const age = undefined; if (age == null) { console.log('โœ… variable is undefined or null'); } console.log(null == undefined); // ๐Ÿ‘‰๏ธ true

Because we use loose equality (==), the condition is met if the age variable is either undefined or null.

This is a bit more implicit than using the strict equality operator and might be confusing to some developers reading your code.

It's generally best to be explicit and direct, than to be implicit and write less intuitive code.

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