How to determine function exists in javascript


To find the equivalent method function_exists of PHP in Javascript, we make some test

1. Use jQuery.isFunction method: we use Chrome Console to test

Eg: load2 and load3 are the functions to check

$.isFunction(load2)
true
$.isFunction("load2")
false
$.isFunction(load3)
VM5946:2 Uncaught ReferenceError: load3 is not defined(…)

jQuery isFunction

So, it’s difficult to determine function exists by using jQuery.isFunction method. However, if you use the try catch statement, we can determine.

try{ check = $.isFunction(load3) }catch(e){ check = false }
false
try{ check = $.isFunction(load2) }catch(e){ check = false }
true

2. Use typeof:

typeof load2=="undefined"
false
typeof load3=="undefined"
true
typeof "load2"=="undefined"
false
typeof "load3"=="undefined"
false
typeof load2
"function"
typeof load3
"undefined"

3. Use eval
If don’t use the try catch statement:

eval("load2()")
undefined
eval("load3()")
VM7363:1 Uncaught ReferenceError: load3 is not defined(…)

If use the try catch statement:

try{ eval("load2()"); check=true }catch(e){ check=false }
true
try{ eval("load3()"); check=true }catch(e){ check=false }
false

Now, we have 3 methods to check function exists in javascript:

Method 1:

try{ check = $.isFunction(function_name) }catch(e){ check = false }

Method 2:

check = (typeof function_name == "function") 

Method 3:

try{ eval("function_name()"); check=true }catch(e){ check=false }

Leave a Reply