How to check if a Variable in JavaScript is undefined or null

← PrevNext →

variable is undefined, (or simply undefined) says the browser console. It’s an error message, which indicates that a variable inside a JavaScript code is declared but has no value. It’s a very common error. There are few simple methods in JavaScript using which you can check or determine if a variable is undefined or null.

Using “null” with the “equality” operator

You can use the equality (==) operator in JavaScript to check if a variable is undefined or null. For example,

var myName;
if (myName == null) 
    alert ('it is null!');
Try it

Here, I have declared a variable called myName. However, I have not assigned any value to it. I am using the null keyword with the equality (==) operator to check if the variable is null.

Using the “undefined” type

In some cases, you can use the undefined keyword to check the variables status. For example,

var myName;
if (myName == undefined) 
    alert ('its undefined');
Try it

It is safe to use the undefined type in your JavaScript code to check the status of a variable. All new browsers support this type.

Remember, a variable however, with a blank value is not undefined or null.

var myName = '';

The variable myName has a value (blank, I would say), but it is neither null nor undefined.

Uncaught ReferenceError: some_variable is not defined

Your browser console may also sometimes show an error and would say, Uncaught ReferenceError: some_variable is not defined. See the bottom of the image.

Check if variable is undefined in JavaScript

Don’t confuse this error with the undefined error that I have explained above. Both are different and have different meanings. In this case, I have not declared (or defined) the variable myName anywhere in my JS code. It does not know if it’s a string, number or a Boolean.

So, to check if a variable is undefined or null, you must first declared or define the variable in your code.

Well, that’s it. Thanks for reading.

← PreviousNext →