Thursday, October 16, 2025
HomeLanguagesJavascriptJavaScript Check the existence of variable

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: 

  • 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
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11953 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS