patternjavascriptCritical
Check if a variable is of function type
Viewed 0 times
functionchecktypevariable
Problem
Suppose I have any variable, which is defined as follows:
I want a function which checks if the type of the variable is function-like. i.e. :
How can I check if the variable
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:
Note: This solution doesn't work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.
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.