How to check undefined variable in JavaScript/jQuery

To check an undefined variable in JavaScript or jQuery, we can use one of these two methods.

Compare variable type to undefined

Compare variable to undefined

Compare variable type to undefined

To check the data type of a variable in JavaScript typeof keyword is used. Below is. The example to check the undefined variable using typeof.

1

2

3

4

5

6

7

8

<script>

if(typeofvar=='undefined'){

alert("var is undefined");

}

if(typeofvar2==='undefined'){

alert("var2 is undefined");

}

</script>

Code explanation: In the code above there are two variables var and var2. First I have used a loose comparison operator to identify if the type of var is equal to undefined and in the second condition, the strict comparison is used to find if the type of var2 is equal to undefined. type of gives the data type of any variable in string form. Click to read more about it.

Compare variable to check undefined

Another method to identify whether the variable is defined or not is to Compare variable to type undefined. Below is the example using this method.

1

2

3

4

5

<script>

if(var===undefined){

alert("varisundefined);

}

</script>

Code explanation: It is notable that in this case undefined is not encapsulated in quotes (” or ‘). Here I am checking if the variable is undefined, while in previous example type of variable was checked.