Open In App

JavaScript Check the existence of variable

Last Updated : 07 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript has a built-in function to check whether a variable is defined/initialized or undefined. To do this, we will use the typeof operator. The typeof operator will return undefined if the variable is not initialized and the operator will return null if the variable is left blank intentionally.
Note: 

  • The typeof operator will check whether a variable is defined or not.
  • The typeof operator doesn’t throw a ReferenceError exception when it is used with an undeclared variable.
  • The typeof null will return an object. So, check for null also.

Example 1: This example checks whether a variable is defined or not. 

Javascript




let GFG_Var;
 
if (typeof GFG_Var === 'undefined') {
    console.log("Variable is Undefined");
}
else {
    console.log("Variable is defined and"
        + " value is " + GFG_Var);
}


Output

Variable is Undefined

Example 2: This example also checks whether a variable is defined or not. 

Javascript




let GFG_Var = "GFG";
 
if (typeof GFG_Var === 'undefined') {
    console.log("Variable is Undefined");
}
else {
    console.log("Variable is defined and"
        + " value is " + GFG_Var);
}


Output

Variable is defined and value is GFG

Example 3: In this example, we will check whether a variable is null or not. 

Javascript




let GFG_Var = null;
 
if (typeof GFG_Var === null) {
    console.log("Variable is null");
}
else {
    console.log("Variable is defined and value is "
        + GFG_Var);
}


Output

Variable is defined and value is null


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads