check if variable exists in js

How to Check if Variable Exists or Is Defined in JS

JavaScript variables are one of the most commonly used data structures in almost every website or application. Often if you try to access a variable that does not exist or is not defined then you will get an error and your JS code execution may stop. So it is advisable to check if variable exists or is defined in JS. In this article, we will learn how to do this.

How to Check if Variable Exists or Is Defined in JS

It is very easy to check if variable exists or not in JavaScript. Just use typeof operator as shown below.

if (typeof variable !== 'undefined') {
    // the variable is defined
}

The typeof operator does not throw ReferenceError when used with undefined or undeclared variable. But it does return an object. So it will return true if your variable is null. If you don’t want your variable to null either, modify the above code as shown below.

if (typeof variable != 'undefined' || variable != null) {
    // variable is undefined or null
}

OR

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

In this article, we have seen a simple way to check if variable exists or is defined. It is always a good practice to check if variables on your pages exist, before you use them, at least the critical ones that can stop your JS code execution.

Also read:

How to Convert UTC Date Time to Local Date Time in JS
How to Use Variable Number of Arguments in JS Function
How to Add 1 Day to Current Date in JS
How to Change One Character in Python String
How to Permanently Add Directory to Python Path

Leave a Reply

Your email address will not be published.