Check if a variable is of function type

Check if a variable is of function type

Suppose I have any variable, which is defined as follows:
var a = function() {/* Statements */};

I want a function which checks if the type of the variable is function-like. i.e. :
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);

How can I check if the variable a is of type Function in the way defined above?

Solutions/Answers:

Solution 1:

Sure underscore’s way is more efficient, but the best way to check, when efficiency isn’t an issue, is written on underscore’s page linked by @Paul Rosania.

Inspired by underscore, the final isFunction function is as follows:

function isFunction(functionToCheck) {
 return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

Solution 2:

if (typeof v === "function") {
    // do something
}

Solution 3:

Underscore.js uses a more elaborate but highly performant test:

_.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
};

See: http://jsperf.com/alternative-isfunction-implementations

EDIT: updated tests suggest that typeof might be faster, see http://jsperf.com/alternative-isfunction-implementations/4

Solution 4:

There are several ways so I will summarize them all

  1. Best way is:
    
    function foo(v) {if (v instanceof Function) {/* do something */} };
    
    

    Most performant (no string comparison) and elegant solution – the instanceof operator has been supported in browsers for a very long time, so don’t worry – it will work in IE 6.

  2. Next best way is:
    
    function foo(v) {if (typeof v === "function") {/* do something */} };
    
    

    disadvantage of typeof is that it is susceptible to silent failure, bad, so if you have a typo (e.g. “finction”) – in this case the `if` will just return false and you won’t know you have an error until later in your code

  3. The next best way is:
    
    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }
    
    

    This has no advantage over solution #1 or #2 but is a lot less readable. An improved version of this is

    
    function isFunction(x) {
        return Object.prototype.toString.call(x) == '[object Function]';
    }
    
    

    but still lot less semantic than solution #1

Solution 5:

jQuery (deprecated since version 3.3) Reference

$.isFunction(functionName);

AngularJS Reference

angular.isFunction(value);

Lodash Reference

_.isFunction(value);

Underscore Reference

_.isFunction(object); 

Node.js deprecated since v4.0.0 Reference

var util = require('util');
util.isFunction(object);

Solution 6:

@grandecomplex: There’s a fair amount of verbosity to your solution. It would be much clearer if written like this:

function isFunction(x) {
  return Object.prototype.toString.call(x) == '[object Function]';
}