So, let’s get started!
The undefined type belongs to the primitive data types that can have only one value i.e. undefined. A variable that is declared/created but not assigned with a value anywhere in the program has a default value of “undefined”.
Example1: variable declared but not defined
In this example, we will check the type of a variable that is declared but not defined anywhere in the program:
In this example:
- We declared/created a variable “x” and didn’t assign it a value.
- Next, we utilized the “typeof” operator to find the type of “x”.
- Consequently, we get the below-given result:
The typeof operator returned undefined which verified that an unassigned variable has a default value of “undefined”.
Example2: type of an empty string
Let’s consider we have an empty string as shown in the below snippet:
The task is to check the type and value of an empty string:
var x = «»;
The above snippet utilized the console.log() method:
- To print the value of x.
- To print the data type of x.
- As a result, we get the below-given output:
The output verified that an empty string and an undefined variable are two different things. The undefined variable has a data type “undefined” while an empty string has a data type “string”.
Example3: check if a variable is defined or not
In this example program, we will check whether a specific variable is defined or not. If the program does not define the variable, display the message “variable not defined!”. Else show the message “variable defined”:
The above code served the below given functionalities:
- Declared a variable “x”.
- Next, compared the value of “x” with the “undefined” type.
- Printed “variable not defined” if the program does not define the variable.
- Else displayed the message “variable defined”: