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?
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:
@grandecomplex: There's a fair amount of verbosity to your solution. It would be much clearer if written like this:
If you use Lodash you can do it with _.isFunction.
This method returns
true
if value is a function, elsefalse
.Underscore.js uses a more elaborate but highly performant test:
See: http://jsperf.com/alternative-isfunction-implementations
EDIT: updated tests suggest that typeof might be faster, see http://jsperf.com/alternative-isfunction-implementations/4
For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.
Next code contains only pure and pointfree functions:
As of ES2017,
async
functions are available, so we can check against them as well:And then combine them together:
Of course, function should be protected against
null
andundefined
values, so to make it "safe":And, complete snippet to sum up:
However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.