jQuery: Check if Function Exists before Calling

This post shows how to check if a function exists, before calling it. We will use both JavaScript as well as jQuery (JavaScript library) to do so.

Using JavaScript

In order to check if a function exists using plain JavaScript, use the following code:

check function exists

The output is the following:

image

Using jQuery

jQuery contains the jQuery.isFunction() which finds out if the parameter passed to it is a function.

<script type="text/javascript">
function
calculateSum() {
}

// using jQuery
if ($.isFunction(window.calculateSum))
calculateSum();
else
document.writeln('calculateSum does not exist');
</script>

Since calculateSum() exists, the method gets called.

Check plenty of similar jQuery/JavaScript tips here






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

6 comments:

Unknown said...

The jQuery example will throw a ReferenceError if the function is not defined. It should be altered to test window.calculateSum as well.

Suprotim Agarwal said...

JFSIII - Thanks for the pointer. It's fixed now. By the way for all inbuilt functions, the following can also be used

if ('data' in $)
alert('$.data exists');
else
alert('$.data does not exists');

Anonymous said...

Thanks for the post...that's a good tip. I wasn't aware of jQuery's "isFunction" method.

I know this is off-topic but I do have a little suggestion regarding your site's tagline: "What's cooking developers?" I think you mean, "What's cooking, developers?" Otherwise, the lack of the comma in the tagline suggests that developers are actually being cooked by some unknown entity. ;)

Not a major issue at all but I thought I'd let you know.
- g

Suprotim Agarwal said...

:) yes that's a good observation. I will get it changed this weekend and add a comma there!

Thanks Anonymous (what's your name?)

psayre23 said...

To test if jQuery has a fuctnion, use:

var hasCss = 'css' in $.fn;
Or
var hasCss = $.isFunction($.fn.css);

Anonymous said...

Although my previous comment suggests that the "g" stands for "Grammar nazi", my name is actually "Gregg". ;)