How to Check If Variable Exists in Javascript

Programmers often have to deal with a lot of variables while coding. Sometimes, the programmer forgets to define the variable and tries to access the variable somewhere in the program. Or sometimes, they try to access those variables that never exist in the code. Yet another time, the programmers often mistyped the variable name to get unwanted errors in the program while compiling.

We usually adopt some techniques to check whether the variable we are working with exists or not in the code. For example, we typically check whether the variable is defined or not, the data type of the variable, etc. This helps us to indirectly check whether the variable exists in the code or not.

In this article, we will discuss how to fix the problem. Indirectly, we will check whether the variable we are using exists or not in the code.

Check if a variable exists in Javascript

To check if a variable exists in JavaScript, use the double equal operator(==) and compare its value to the undefined. The == operator treats an empty string as 0 in number. Not initialized string as the not defined equivalent of number etc.

A variable exists in the code only if it is defined. So if we can check whether a variable exists in the code, we can check whether the variable is previously defined in the code.

We can check whether a variable exists or not using the == operator and checking whether it is equal to undefined in javascript. We can also use the === operator instead of the == operator.

The main difference between == and === is that the first one is not a strict operator. It will convert the data types of both variables before checking for equality. The variables are not tried to make the same data types in the second data type.

Example 1

let data = "Helly my name is Max";

if (data == undefined) {

 console.log("Sorry the data is undefined")

}

else {

 console.log("The data variable is defined.")

}

Output

The data variable is defined.

Explanation

In the above code, there exists a variable named “name” in the code. Hence the variable is already defined in the program beforehand. We used the condition of whether the variable is defined or not in the program. Since the variable is defined, the condition returned false.

Example 2

let data;

if (data == undefined) {

 console.log("Sorry, the data is undefined.")

}

else {

 console.log("The data variable is defined.")

}

Output

Sorry, the data is undefined.

Explanation

In the above code, although we have defined a variable, we have not specified any value to the variable. Hence the condition returned true. This is because the compiler treats the variable “name” as undefined.

Using typeof operator in JavaScript

A tricky method to achieve whether the variable exists in JavaScript is using the typeof() function. The typeof() is a built-in JavaScript function that returns the data types of the variable. The main data types in JavaScript are boolean, number, string, objects, symbols, etc.

Suppose we are trying to access the data type of a variable, and the variable does not exist in the code. Then obviously, the truth value of the condition will be evaluated as false since no such variable exists in the code.

Example 1

var data = "Hello my name is Drake";

var flag = false;

var num = 98;

var symbol = '%';

const obj = {

 myname: "Drake",

 rollNumber: 08987655,

 address: "34 jonson road newyork"

};

console.log(typeof (data));

console.log(typeof (flag));

console.log(typeof (num));

console.log(typeof (symbol));

console.log(typeof (obj));

Output

string

boolean

number

string

object

Explanation

In the above code, we have defined all the variables beforehand, and hence the variables exist in the program. So the javascript will return the type of the respective variables in the console.

Example 2

var data;

var flag;

var num;

var symbol;



console.log(typeof (data));

console.log(typeof (flag));

console.log(typeof (num));

console.log(typeof (symbol));

console.log(typeof (obj));

Output

undefined

undefined

undefined

undefined

undefined

Explanation

In the above code, although we have initialized the variables, we haven’t stored the values in the 

Variable hence javascript returned undefined. Although initialized, all the variables, namely name, flag, num, and symbol, have not been assigned values. The last variable, obj, has not been initialized nor declared in the code; hence, they are all treated as undefined in javascript.

Using typeof operator with strict comparison(===)

if (typeof variable === 'undefined') 
{
 // The given variable is undefined.
}

typeof operator checks if a variable is defined/null, but it doesn’t throw a ReferenceError exception when used with an undeclared variable. Don’t forget that the typeof null will return “object”.

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

Example

let sum;
if (typeof sum === 'undefined' || sum === null) {
 console.log("The given variable is undefined or null.")
}

Output

The given variable is undefined or null.

Conclusion

In the above article, we have learned methods to check whether a variable exists in the code or not. However, programmers often deal with this issue while programing and hence need to check the issue while debugging. 

While informally writing the codes, it is not much difficult to check whether the variable exists or not because the code lines are too small. However, in industry, the codes and variable names are so confusing that the programmer has to adopt such methods to check, and later they remove the piece of code.

Related posts

How to Check If a Variable is an Array in JavaScript

How to Check null Value in Javascript

How to Check undefined in JavaScript

JavaScript null vs undefined

Leave a Comment