jQuery

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

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:

//If value of  show_cities is NOT undefined, that means that value exists, so we show cities list.

if( typeof show_cities != 'undefined' )
{
$('#city_id').show();
}
else
{
$('#city_id').hide();
}

You may also rewrite the above code as

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

//If value of  show_cities is Undefined, that means that value is not set, so we hide cities list.

if( typeof show_cities === 'undefined' )
{
$('#city_id').hide();
}
else
{
$('#city_id').show();
}
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.

Share your thoughts, comment below now!

*

*