JavaScript - Undefined Check



When the value is absolutely not present in the variable or string or anything else, we call it as Undefined. In JavaScript, undefined is a one of the primitive data type. It is used to represent the absence of a value.

It get assigned to a variable when it is declared but not assigned any value.

How to check if a variable is undefined?

There are more than one way to check if a variable is undefined or not. Let's see them one by one.

  • Using typeof operator
  • Using strict equality operator
  • Using void operator

Using typeof operator

When the variable is undefined, it means the variable is not declared. Users cant use it in the if-else conditional statement like the above method.

To check the type of the undeclared variables, we can use the typeof operator. The typeof operator takes the variable as an operand and returns the variable type. As the operand of typeof, we can use undeclared variables also.

Syntax

Below syntax is used to check undefined variable using the typeof operator.

typeof variable_name === 'undefined'

Example

Below is the example code given, that shows how to use the typeof operator to check the undefined value of the variable.

<html>
<body>
<script>
var a;
if(typeof a === 'undefined'){
document.write('a is undefined');
}
</script>
</body>
</html>

Output

Following is the output of the above code

a is undefined

Using strict equality operator

In this method, we will use the strict equality operator to check whether a variable is null, empty, or undefined. If we dont assign the value to the variable while declaring, the JavaScript compiler assigns it to the undefined value. So, we can check that if the variable contains the null value or undefined value, it means we have a null variable.

Syntax

Below is the syntax given for checking the undefined value of the variable using the strict equality operator.

variable_name === undefined

Example

<html>
<body>
<script>
var a;
if(a === undefined){
document.write('a is undefined');
}
</script>
</body>
</html>

Output

Following is the output of the above code

a is undefined
Advertisements