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. 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.
html
< h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > variable-name : GFG_Var </ p > < button onclick = "myGeeks()" > Check </ button > < h3 id = "div" style = "color:green;" ></ h3 > < script > function myGeeks() { var GFG_Var; var h3 = document.getElementById("div"); if (typeof GFG_Var === 'undefined') { h3.innerHTML = "Variable is Undefined"; } else { h3.innerHTML = "Variable is defined and" + " value is " + GFG_Var; } } </ script > |
Output:

Example 2: This example also checks whether a variable is defined or not.
html
< h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > variable-name : GFG_Var </ p > < button onclick = "myGeeks()" > Check </ button > < h3 id = "div" style = "color:green;" ></ h3 > < script > function myGeeks() { var GFG_Var = "GFG"; var h3 = document.getElementById("div"); if (typeof GFG_Var === 'undefined') { h3.innerHTML = "Variable is Undefined"; } else { h3.innerHTML = "Variable is defined and" + " value is " + GFG_Var; } } </ script > |
Output:

Example 3: In this example, we will check whether a variable is null or not.
html
< h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > variable-name : GFG_Var </ p > < button onclick = "myGeeks()" > Check </ button > < h3 id = "div" style = "color:green;" ></ h3 > <!-- Script to check existence of variable --> < script > function myGeeks() { var GFG_Var = null; var h3 = document.getElementById("div"); if (typeof GFG_Var === null ) { h3.innerHTML = "Variable is null"; } else { h3.innerHTML = "Variable is defined and value is " + GFG_Var; } } </ script > |
Output:

Please Login to comment...