Check if Variable is Set or Not (Undefined) using jQuery

In jQuery, Tips and Tricks by October 26th, 2012

1770 Views

Ever wondered how to Check if Variable is Set or Not using jQuery? If yes, then this article is for you. At times, it may be very important to check if a variable is Undefined or if already contains some value so that you can perform related operations. You may encounter such a case when you are creating javascript variables dynamically. So in order to avoid breaking your code, at the proper stages, it can be very helpful to first check if a variable value is set or not. To find out how to do so, read on.

Using jQuery to Check if Variable is Set or Not (Undefined)

Lets discuss this situation with a practical example. Let’s assume that I have a dropdown of cities that I want to show/hide depending upon the value of a variable. So let’s call this variable “show_cities”. If the value of this variable is 1, then I would like to show the cities. If the value is not set or undefined, I don’t want to show the cities list. Let’s assume that the cities list is populated in a dropdown with ID “city_id”.

Example 1: Check if Variable Undefined or Not set using jQuery:

You may also rewrite the above code as

Example 2: Check if Variable Undefined or Not set using jQuery:

Easy, heh?

Do you know of any other ways to check if a variable is set or not or defined/undefined using jQuery? Feel free to share by commenting below.