Signup/Sign In

How to check if a variable exists or defined in JavaScript

Answer: Using typeof operator

There are several ways to check if a variable exists or is defined in JavaScript or not. We can check this by using typeof operator. The reason behind using typeof operator is that it does not throw the reference error when the variable is not declared.

The typeof operator specifies the type of the variable. The type of any variable can be one of the following values boolean, number, string, symbol, object, function, and undefined.

Example

In the given example, we have used the type of operator to check whether the variable is defined or not. The typeof operator does not throw the Reference error when the variable is not defined.

<script>
  console.log(typeof myVar); // Doesn't throw ReferenceError

  console.log(myVar);   // throws ReferenceError
</script>

Output

image

We can use the strict equality (===) operator to check whether the variable is defined or not. This method can also consider the variable undefined when the variable is defined but not initialized.

Example: Using strict equality (===) operator

In the given example, we have used the typeof operator along with the strict equality operator to check whether the variable exists or not.

<script>
  if (typeof myVar === 'undefined') {
   console.log('The variable myVar is undefined');
} else {
  console.log('The variable myVar is defined');
}
</script>

Output


The variable myVar is undefined

The above example can also consider the variable undefined when the variable is defined but not initialized.

In the above example, if the variable is defined but not initialize, then that variable is considered as undefined. To overcome this problem, we are going to compare the variable with an undefined keyword using the strict equality (===) operator.

Example: Using the undefined keyword

In the given example, we have checked whether a variable exists or not when the variable is defined but not initialize.

<!DOCTYPE html>
<html>
 <head>
    <title>Check if a variable exists or defined</title>
</head>
<body>
<script>
  var myVar;
  if (typeof myVar === 'undefined') {
    console.log('The variable myVar is undefined');
  } 
  else {
    console.log('The variable myVar is defined');
  }

  var num = 24;
  if (typeof num === 'undefined') {
   console.log('The variable num is undefined');
  } 
  else {
   console.log('The variable num is defined'); 
  }
</script>
</body>
</html>     

Output

image

Conclusion

In this lesson, we have learned how to check if a variable exists or is defined in JavaScript. So we have used the typeof operator along with the strict equality (===) operator to check whether the variable exists or is defined.



About the author: