Open In App

JavaScript Check the existence of variable

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: 

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




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. 




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. 




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

Article Tags :