Thursday, September 4, 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
32262 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11856 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS