jQuery How to check undefined variable in JavaScript/jQuery

How to check undefined variable in JavaScript/jQuery

How to check undefined in JavaScript/jQuery

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

  1. Compare variable type to undefined
  2. 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.

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.

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.

Leave a Reply