jQuery isFunction check error "function is not defined"

JqueryFunction

Jquery Problem Overview


I want to do a check whether a function exist or not before trying to run it. Here is my code:

if ($.isFunction(myfunc())) {
    console.log("function exist, run it!!!");
}

However, when the function is not available I got the error: > myfunc is not defined

How can I do the detection? Here is my working test: http://jsfiddle.net/3m3Y3/

Jquery Solutions


Solution 1 - Jquery

By putting () after the function name, you're actually trying to run it right there in your first line.

Instead, you should just use the function name without running it:

if ($.isFunction(myfunc)) {

However - If myfunc is not a function and is not any other defined variable, this will still return an error, although a different one. Something like myfunc is not defined.

You should check that the name exists, and then check that it's a function, like this:

if (typeof myfunc !== 'undefined' && $.isFunction(myfunc)) {

Working example here: http://jsfiddle.net/sXV6w/

Solution 2 - Jquery

try this

if(typeof myfunc == 'function'){
    alert("exist");
}else{
    alert("not exist");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1995781View Question on Stackoverflow
Solution 1 - JqueryjcsanyiView Answer on Stackoverflow
Solution 2 - Jqueryuser2249160View Answer on Stackoverflow