How to tell if a JavaScript function is defined

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.

Solutions/Answers:

Solution 1:

typeof callback === "function"

Solution 2:

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.

Solution 3:

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.

Solution 4:

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);
}

Solution 5:

New to JavaScript I am not sure if the behaviour has changed but the solution given by Jason Bunting (6 years ago) won’t work if possibleFunction is not defined.

function isFunction(possibleFunction) {
  return (typeof(possibleFunction) == typeof(Function));
}

This will throw a ReferenceError: possibleFunction is not defined error as the engine tries to resolve the symbol possibleFunction (as mentioned in the comments to Jason’s answer)

To avoid this behaviour you can only pass the name of the function you want to check if it exists. So

var possibleFunction = possibleFunction || {};
if (!isFunction(possibleFunction)) return false;

This sets a variable to be either the function you want to check or the empty object if it is not defined and so avoids the issues mentioned above.

Solution 6:

Try:

if (typeof(callback) == 'function')