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 data type of a variable in JavaScript typeof keyword is used. Below is. The example to check undefined variable using typeof.

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

Compare variable to check undefined

Other method to check if a variable is undefined is to Compare variable to type undefined. Below is the example using this method.

Code explaination: It is noteable 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.

Share your thoughts

avatar
  Subscribe  
Notify of