How to tell if a JavaScript function is defined
typeof callback === "function"
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.
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.