50

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/

7ochem
  • 2,183
  • 1
  • 34
  • 42
user1995781
  • 19,085
  • 45
  • 135
  • 236

2 Answers2

138

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/

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
  • 1
    Thanks for your answer, but it still doesn't work. I have tested it here: http://jsfiddle.net/3m3Y3/ – user1995781 Nov 17 '13 at 06:04
  • @user1995781 you need to quote the word `'undefined'` – Petah Jul 24 '14 at 07:45
  • 9
    this doesn't work for jQuery dependency plugins, `if (!!$.prototype.functionName)` worked for me, check the answer [here](http://stackoverflow.com/questions/5108832/jquery-test-for-whether-an-object-has-a-method) – Vikas Khunteta Jan 11 '15 at 14:53
  • Can also use ```if (typeof myfunc === 'function')``` – chris c Nov 08 '19 at 01:19
13

try this

if(typeof myfunc == 'function'){
    alert("exist");
}else{
    alert("not exist");
}
Ihsahs
  • 892
  • 9
  • 23