[javascript] 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.

This question is related to javascript reflection

The answer is


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.


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.


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.


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.


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.


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.


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

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

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.


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.


Try:

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

Try:

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

Try:

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

Try:

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

typeof(callback) == "function"

typeof(callback) == "function"

typeof(callback) == "function"

typeof(callback) == "function"

I might do

try{
    callback();
}catch(e){};

I know there's an accepted answer, but no one suggested this. I'm not really sure if this fits the description of idiomatic, but it works for all cases.

In newer JavaScript engines a finally can be used instead.


I might do

try{
    callback();
}catch(e){};

I know there's an accepted answer, but no one suggested this. I'm not really sure if this fits the description of idiomatic, but it works for all cases.

In newer JavaScript engines a finally can be used instead.


function something_cool(text, callback){
    alert(text);
    if(typeof(callback)=='function'){ 
        callback(); 
    };
}

function something_cool(text, callback){
    alert(text);
    if(typeof(callback)=='function'){ 
        callback(); 
    };
}

function something_cool(text, callback){
    alert(text);
    if(typeof(callback)=='function'){ 
        callback(); 
    };
}

function something_cool(text, callback){
    alert(text);
    if(typeof(callback)=='function'){ 
        callback(); 
    };
}

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

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

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

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

Try:

if (!(typeof(callback)=='undefined')) {...}

Try:

if (!(typeof(callback)=='undefined')) {...}

Try:

if (!(typeof(callback)=='undefined')) {...}

Try:

if (!(typeof(callback)=='undefined')) {...}

Try this:

callback instanceof Function

Try this:

callback instanceof Function

If you look at the source of the library @Venkat Sudheer Reddy Aedama mentioned, underscorejs, you can see this:

_.isFunction = function(obj) {
  return typeof obj == 'function' || false;
};

This is just my HINT, HINT answer :>


If you look at the source of the library @Venkat Sudheer Reddy Aedama mentioned, underscorejs, you can see this:

_.isFunction = function(obj) {
  return typeof obj == 'function' || false;
};

This is just my HINT, HINT answer :>


If you use http://underscorejs.org, you have: http://underscorejs.org/#isFunction

_.isFunction(callback);

If you use http://underscorejs.org, you have: http://underscorejs.org/#isFunction

_.isFunction(callback);

I was looking for how to check if a jQuery function was defined and I didn't find it easily.

Perhaps might need it ;)

if(typeof jQuery.fn.datepicker !== "undefined")

I was looking for how to check if a jQuery function was defined and I didn't find it easily.

Perhaps might need it ;)

if(typeof jQuery.fn.datepicker !== "undefined")

Most if not all previous answers have side effects to invoke the function

here best practice

you have function

_x000D_
_x000D_
function myFunction() {_x000D_
        var x=1;_x000D_
    }
_x000D_
_x000D_
_x000D_ direct way to test for it

_x000D_
_x000D_
//direct way_x000D_
        if( (typeof window.myFunction)=='function')_x000D_
            alert('myFunction is function')_x000D_
        else_x000D_
            alert('myFunction is not defined');
_x000D_
_x000D_
_x000D_ using a string so you can have only one place to define function name

_x000D_
_x000D_
//byString_x000D_
        var strFunctionName='myFunction'_x000D_
        if( (typeof window[strFunctionName])=='function')_x000D_
            alert(s+' is function');_x000D_
        else_x000D_
            alert(s+' is not defined');
_x000D_
_x000D_
_x000D_


Most if not all previous answers have side effects to invoke the function

here best practice

you have function

_x000D_
_x000D_
function myFunction() {_x000D_
        var x=1;_x000D_
    }
_x000D_
_x000D_
_x000D_ direct way to test for it

_x000D_
_x000D_
//direct way_x000D_
        if( (typeof window.myFunction)=='function')_x000D_
            alert('myFunction is function')_x000D_
        else_x000D_
            alert('myFunction is not defined');
_x000D_
_x000D_
_x000D_ using a string so you can have only one place to define function name

_x000D_
_x000D_
//byString_x000D_
        var strFunctionName='myFunction'_x000D_
        if( (typeof window[strFunctionName])=='function')_x000D_
            alert(s+' is function');_x000D_
        else_x000D_
            alert(s+' is not defined');
_x000D_
_x000D_
_x000D_


This worked for me

if( cb && typeof( eval( cb ) ) === "function" ){
    eval( cb + "()" );
}

This worked for me

if( cb && typeof( eval( cb ) ) === "function" ){
    eval( cb + "()" );
}

If the callback() you are calling not just for one time in a function, you could initialize the argument for reuse:

callback = (typeof callback === "function") ? callback : function(){};

For example:

function something_cool(text, callback) {
    // Initialize arguments
    callback = (typeof callback === "function") ? callback : function(){};

    alert(text);

    if (text==='waitAnotherAJAX') {
        anotherAJAX(callback);
    } else {
        callback();
    }
}

The limitation is that it will always execute the callback argument although it's undefined.


If the callback() you are calling not just for one time in a function, you could initialize the argument for reuse:

callback = (typeof callback === "function") ? callback : function(){};

For example:

function something_cool(text, callback) {
    // Initialize arguments
    callback = (typeof callback === "function") ? callback : function(){};

    alert(text);

    if (text==='waitAnotherAJAX') {
        anotherAJAX(callback);
    } else {
        callback();
    }
}

The limitation is that it will always execute the callback argument although it's undefined.


For global functions you can use this one instead of eval suggested in one of the answers.

var global = (function (){
    return this;
})();

if (typeof(global.f) != "function")
    global.f = function f1_shim (){
        // commonly used by polyfill libs
    };

You can use global.f instanceof Function as well, but afaik. the value of the Function will be different in different frames, so it will work only with a single frame application properly. That's why we usually use typeof instead. Note that in some environments there can be anomalies with typeof f too, e.g. by MSIE 6-8 some of the functions for example alert had "object" type.

By local functions you can use the one in the accepted answer. You can test whether the function is local or global too.

if (typeof(f) == "function")
    if (global.f === f)
        console.log("f is a global function");
    else
        console.log("f is a local function");

To answer the question, the example code is working for me without error in latest browers, so I am not sure what was the problem with it:

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

Note: I would use callback !== undefined instead of callback != null, but they do almost the same.


For global functions you can use this one instead of eval suggested in one of the answers.

var global = (function (){
    return this;
})();

if (typeof(global.f) != "function")
    global.f = function f1_shim (){
        // commonly used by polyfill libs
    };

You can use global.f instanceof Function as well, but afaik. the value of the Function will be different in different frames, so it will work only with a single frame application properly. That's why we usually use typeof instead. Note that in some environments there can be anomalies with typeof f too, e.g. by MSIE 6-8 some of the functions for example alert had "object" type.

By local functions you can use the one in the accepted answer. You can test whether the function is local or global too.

if (typeof(f) == "function")
    if (global.f === f)
        console.log("f is a global function");
    else
        console.log("f is a local function");

To answer the question, the example code is working for me without error in latest browers, so I am not sure what was the problem with it:

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

Note: I would use callback !== undefined instead of callback != null, but they do almost the same.


If you wish to redefine functions, it is best to use function variables, which are defined in their order of occurrence, since functions are defined globally, no matter where they occur.

Example of creating a new function that calls a previous function of the same name:

A=function() {...} // first definition
...
if (typeof A==='function')
   oldA=A;
A=function() {...oldA()...} // new definition

If you wish to redefine functions, it is best to use function variables, which are defined in their order of occurrence, since functions are defined globally, no matter where they occur.

Example of creating a new function that calls a previous function of the same name:

A=function() {...} // first definition
...
if (typeof A==='function')
   oldA=A;
A=function() {...oldA()...} // new definition

One-line solution:

function something_cool(text, callback){
    callback && callback();
}

One-line solution:

function something_cool(text, callback){
    callback && callback();
}

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with reflection tag:

Get properties of a class Get class name of object as string in Swift Set field value with reflection Using isKindOfClass with Swift I want to get the type of a variable at runtime Loading DLLs at runtime in C# How to have Java method return generic list of any type? Java reflection: how to get field value from an object, not knowing its class Dynamically Add C# Properties at Runtime Check if a property exists in a class Reflection generic get field value Call static method with reflection How to check if variable's type matches Type stored in a variable How do I check if a property exists on a dynamic anonymous type in c#? Get property value from C# dynamic object by string (reflection?) Purpose of Activator.CreateInstance with example? Tool to generate JSON schema from JSON data Converting Integer to Long Reflection - get attribute name and value on property Get list of a class' instance methods Creating an instance using the class name and calling constructor What could cause java.lang.reflect.InvocationTargetException? How to get a property value based on the name Get all inherited classes of an abstract class How to check whether an object has certain method/property? Convert a python 'type' object to a string How to determine if a type implements an interface with C# reflection Mapping object to dictionary and vice versa Check if a Class Object is subclass of another Class Object in Java How to get annotations of a member variable? Getting assembly name Get properties and values from unknown object Using PropertyInfo to find out the property type String replacement in java, similar to a velocity template Get generic type of class at runtime Change private static final field using Java reflection How do I get the calling method name and type using reflection? How to get the fields in an Object via reflection? Get name of property as a string How do I check if a type is a subtype OR the type of an object? Best way of invoking getter by reflection How do I reflect over the members of dynamic object? Java - Get a list of all Classes loaded in the JVM Invoking a static method using reflection Open Source Alternatives to Reflector? Getting Class type from String How to get a list of properties with a given attribute? Can I obtain method parameter name using Java reflection? Using reflection in Java to create a new instance with the reference variable type set to the new instance class name? Reflection: How to Invoke Method with parameters