Aaron Lee
Aaron Lee

Reputation: 5457

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.

Upvotes: 357

Views: 222547

Answers (24)

Anuradha Jayasena
Anuradha Jayasena

Reputation: 27

This is what worked for me it always better to check whether 'undefined' at first

if(typeof ShowDialogOpen != 'undefined' && typeof ShowDialogOpen==='function'){
  console.log('function available');
}
else{
  console.log('function NOT available');
}

Upvotes: 0

Darren G
Darren G

Reputation: 868

Using optional chaining with function calls you could do the following:

function something_cool(text, callback) {
    alert(text);
    callback?.();
}

If callback is a function, it will be executed.

If callback is null or undefined, no error is thrown and nothing happens.

However, if callback is something else e.g. a string or number, a TypeError will still be thrown.

Upvotes: 13

Michel Casabianca
Michel Casabianca

Reputation: 1

I would rather suggest following function:

function isFunction(name) {
    return eval(`typeof ${name} === typeof Function`);
}

Upvotes: -1

Patrick Ogbuitepu
Patrick Ogbuitepu

Reputation: 1

This worked for me

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

Upvotes: 0

David Spector
David Spector

Reputation: 1671

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

Upvotes: 0

TexWiller
TexWiller

Reputation: 311

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

here best practice

you have function

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

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

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

Upvotes: 1

Quentin Engles
Quentin Engles

Reputation: 2832

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.

Upvotes: 8

Brian
Brian

Reputation: 3575

Try:

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

Upvotes: 4

bdukes
bdukes

Reputation: 155925

Try:

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

Upvotes: 8

inf3rno
inf3rno

Reputation: 26139

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.

Upvotes: 0

Nick Tsai
Nick Tsai

Reputation: 4129

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.

Upvotes: 1

Reputation:

typeof(callback) == "function"

Upvotes: 5

Tom Ritter
Tom Ritter

Reputation: 101330

typeof callback === "function"

Upvotes: 561

VentyCZ
VentyCZ

Reputation: 61

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 :>

Upvotes: 2

Samir Alajmovic
Samir Alajmovic

Reputation: 3283

One-line solution:

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

Upvotes: -2

Jason Bunting
Jason Bunting

Reputation: 58931

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.

Upvotes: 251

miguelmpn
miguelmpn

Reputation: 2017

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")

Upvotes: 1

Sudheer Aedama
Sudheer Aedama

Reputation: 2144

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

_.isFunction(callback);

Upvotes: 2

Russell Ormes
Russell Ormes

Reputation: 533

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.

Upvotes: 6

eflorico
eflorico

Reputation: 3629

Try this:

callback instanceof Function

Upvotes: 2

Robin like the bird
Robin like the bird

Reputation: 752

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.

Upvotes: 20

patriciorocca
patriciorocca

Reputation: 137

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

Upvotes: 10

Andrew Hedges
Andrew Hedges

Reputation: 21796

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

Upvotes: 4

ConroyP
ConroyP

Reputation: 41906

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

Upvotes: 4

Related Questions