Check if a variable is of function type
Solution 1:
if (typeof v === 'function') {
// do something
}
Solution 2:
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.
Solution 3:
There are several ways so I will summarize them all
- 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. - Next best way is:
function foo(v) {if (typeof v === "function") {/* do something */} };
disadvantage oftypeof
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 - 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 isfunction isFunction(x) { return Object.prototype.toString.call(x) == '[object Function]'; }
but still lot less semantic than solution #1
Solution 4:
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