HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Check if a variable is of function type

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functionchecktypevariable

Problem

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?

Solution

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]';
}


Note: This solution doesn't work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.

Code Snippets

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

Context

Stack Overflow Q#5999998, score: 449

Revisions (0)

No revisions yet.