just use typeof .
typeof(foobar) // -> undefined typeof(alert) // -> function
However, you cannot define a function based on typeof, because you will need to pass an identifier that may not exist. Therefore, if you define function isfun(sym) { return typeof(sym) } and then try to call isfun(inexistent) , your code will be tossed.
The most interesting thing about typeof is that it is an operator, not a function. Therefore, you can use it to check for a character that is not defined without metalization.
if you accept a function in the global scope (i.e. not within a closure), you can define a function to test it as follows:
function isfun(identifier) { return typeof(window[identifier]) == 'function'; }
Here you pass the string for the id, therefore:
isfun('alert'); // -> true isfun('foobar'); // -> false
closing?
Here is an example of a function defined in a closure. Here the printed value will be false , which is incorrect.
(function closure() { function enclosed() {} print(isfun('enclosed')) })()
source share