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?
I found that when testing native browser functions in IE8, using
toString
,instanceof
, andtypeof
did not work. Here is a method that works fine in IE8 (as far as I know):Alternatively, you can check for native functions using:
Though, I have read somewhere that this will not always work in IE7 and below.
Try instanceof: It seems that all functions inherit from the "Function" class:
The solution as some previous answers has shown is to use typeof. the following is a code snippet In NodeJs,
The below seems to work for me as well (tested from
node.js
):There are several ways so I will summarize them all
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