How to tell if a JavaScript function is defined
How do you tell if a function in JavaScript is defined?
I want to do something like this
function something_cool(text, callback) {
alert(text);
if( callback != null ) callback();
}
But it gets me a
callback is not a function
error when callback is not defined.
typeof callback === "function"
All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):
function isFunction(possibleFunction) {
return typeof(possibleFunction) === typeof(Function);
}
Personally, I try to reduce the number of strings hanging around in my code...
Also, while I am aware that typeof
is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.
if (callback && typeof(callback) == "function")
Note that callback (by itself) evaluates to false
if it is undefined
, null
, 0
, or false
. Comparing to null
is overly specific.
Those methods to tell if a function is implemented also fail if variable is not defined so we are using something more powerful that supports receiving an string:
function isFunctionDefined(functionName) {
if(eval("typeof(" + functionName + ") == typeof(Function)")) {
return true;
}
}
if (isFunctionDefined('myFunction')) {
myFunction(foo);
}
Try:
if (typeof(callback) == 'function')