How can I check whether a variable is defined in JavaScript?

Front End TechnologyJavascriptWeb Development

In this tutorial, we will learn to check the existence of the variable, which means whether the variable is declared and initialized or not in JavaScript. In many scenarios, JavaScript programmers need to check the presence of the variable. Otherwise, it throws a reference error if we use it without declaring or defining it.

For example, Programmers have defined the variable and it is uninitialized. Programmers want to change the variables' value through the data they will get from API calls. Suppose that the value of the uninitialized variable is not updated due to some error during the API call. If the programmer tries to access the uninitialized variable without checking its value, it will throw an error.

Before we move ahead, let’s clarify the difference between the defined and undefined, and null variables.

Const data = 10; //variable is declared and defined (initialized with value 10)
Const data; //variable is declared but its value is undefined.
Const data = null; // declared and defined (initialized with "null" value).
data = 10; // undeclared but defined (initialized with 10).
data // undeclared and undefined, type of the variable is undefined

So, now users can clearly understand that if the variable is not initialized, its default value is “undefined.” If we initialize the variable with a “null” value, we can call it a null variable. If users use the undefined or null variables in the code, they have to face the error.

We have different ways to check whether the variable is “undefined”.

  • Using the typeof Operator
  • Using the if statement
  • Use the window.hasOwnProperty() method
  • Use the try/catch block

Using the typeof Operator

The typeof operator is helpful to get the data type of any variable. For undefined variables, the typeof operator returns the string “undefined”. We can use the string equality (“===”) operator, and we can compare the returned value from the typeof operator with the “undefined” string and check the existence of the variable.

Syntax

Users can follow the below syntax to use the typeof operator.

typeof variable_name

Parameters

  • variable_name − It could be any variable for which we want to check whether it is undefined or not.

In general, if we use an undefined variable as an operand of typeof variable, i.e. ‘typeof undefined_variable,’ it doesn’t throw an error, but if we use it at any other place in our code, it throws an error.

Example 1

The below example demonstrates how to check if variable is defined or undefined using the typeof operator. The variable age is declared but assigned with a value so it is defined.

<html>
<head>
   <title> Check if variable is defined or not </title>
</head>
<body>
   <h2>The <i>typeof</i> operator: Check if variable is defined or not</h2>
   <div id="contentDiv"></div>
   <script type="text/javascript">
      let age = 20;
      let contentDiv = document.getElementById("contentDiv");
      if (typeof age === "undefined") {
         contentDiv.innerHTML = " variable <i> age </i> is undefined. ";
      } else {
         contentDiv.innerHTML = "Variable <i> age </i> is defined. ";
      }
   </script>
   <p> Here the variable <i>age</i> is declared with value 20. </p>
</body>
</html>

In the above output, users can see that we have declared the "age" variable, and its value is initialized with 20, so it prints the output as defined.

Try the above program with the following-

var age; // undefined
age = 20; // defined
var age = 20; // defined
var age = null; // defined
age; // Uncaught ReferenceError: age is not defined (in Console)

Please refer to this article to find the difference between undefined and not defined.

Using the if statement

We can check if a variable is ‘defined’ or ‘undefined’ using the if statement. You need to check using the following syntax.

Syntax

if (variable_name === undefined){
   //block of code to be executed.
}

Parameters

  • variable_name − It should be the name of the variable for which we want to check if it is defined or not.

Here the variable_name===undefined is the condition of the if statement. If the variable_name is undefined the result of the condition is “true”, else the result of the condition is “false”. Look at the below example.

Example 2

<html>
<body>
   <h2>The <i>if</i> statement: Check if variable is defined or not </h2>
   <div id = "contentDiv" > </div>
   <script>
      var rank;
      let contentDiv = document.getElementById("contentDiv" );
      if(rank===undefined){
         contentDiv.innerHTML = " variable <i> rank </i> is undefined. ";
      } else{
         contentDiv.innerHTML = " variablle <i> rank </i> is defined. ";
      }
   </script>
</body>
</html>

In the above output, users can see that we have declared the "rank" variable, but its value is uninitialized, so it prints the output as undefined.

Use the window.hasOwnProperty() method

We can access every globally defined variable, object, or function using the window property in JavaScript. The “window” works as a global object to check any variable's existence. We can call the hasOwnProperty() method for the window object to confirm that it contains the variable. It returns a boolean value according to whether a variable is defined or not.

Syntax

let isUndefined = window.hasOwnProerty('variable_name').

Parameters

  • variable_name − It should be the name of the variable for which we want to check if it is defined or not.

Return − It returns “true” if the variable_name exists (either defined or declared), else it returns “false

Example 3

The below example demonstrates how we can check variable is undefined using the window.hasOwnProperty() method.

<html>
<head>
   <title> Check if variable is defined or not </title>
</head>
<body>
   <h2>The <i> window.hasOwnProperty()</i > method</h2>
   <p>Checking the existence of a variable</p>
   <div id="variableDiv"></div>
   <script type="text/javascript">
      // isdefined variable either get true or false value
      var isdefined = window.hasOwnProperty('data');
      let variableDiv = document.getElementById("variableDiv");

      // function to check if variable is undefined or not.
      function checkExistanceOfVar() {
         if (isdefined) {
            variableDiv.innerHTML = " Variable <i> data </i> exist ";
         } else {
            variableDiv.innerHTML = " Variable <i> data </i> doesn't exist ";
         }
      }

      // call the function
      checkExistanceOfVar();
   </script>
</body>
</html>

In the above output, users can see that ‘data’ variable doesn’t exit, so the window.hasOwnProerty() method returns false and control goes to the else block.

However, above method will not work with the let and const variables. Users can use above method to check existence of functions and variable declared with the var keyword.

Use the try/catch block

Generally, we use the try/catch block to save our code from crashing with an unknown error. The JavaScript returns the reference error when the variable is undefined or uninitialized. We can try to access the variable in the try block, and if any error occurs or the variable is undefined, control goes to the catch block, and we can resolve the error there.

Syntax

Users can follow the below syntax for the try/catch block.

try{
   let data = res;
} catch ( error ) {
   // control goes here if variable is undefined without
   // completing the try block
}

Example 4

In the below example, we have demonstrated how to use try/catch block to check whether variable is undefined or not.

<html>
<head>
   <title> Check if variable is defined or not </title>
</head>
<body>
   <h2>Checking if the variable id defined using the <i>try / catch</i> block.</h2>
   <div id="errorDiv"></div>
   <script type="text/javascript">
      let errorDiv = document.getElementById("errorDiv");
      function checkExistanceOfVar() {
         // using the try/catch block
         try {
            let data = result;
            errorDiv.innerHTML = " <i> result </i> variable exist";
         } catch (error) {
            errorDiv.innerHTML = error;
         }
      }

      // call the function
      checkExistanceOfVar();
   </script>
</body>
</html>

In the above example, we are trying to assign undefined result variable to the data variable, so control goes to the catch block and it prints the ReferenceError.

Conclusion

We have seen three different approaches to checking whether a variable is undefined. The first approach is applicable in all conditions. Users can use the second approach only with the variable declared with the ‘var’ keyword. While using the third approach, users need to specify the error type in the catch block. Otherwise, control goes to the catch block due to other errors.

raja
Updated on 12-Jul-2022 13:58:45

Advertisements