Suppose I have any variable, which is defined as follows:
var a = function() {/* Statements */};
I want a function which checks if the type
var foo = function(){};
if (typeof foo === "function") {
alert("is function")
}
If you use Lodash you can do it with _.isFunction.
_.isFunction(function(){});
// => true
_.isFunction(/abc/);
// => false
_.isFunction(true);
// => false
_.isFunction(null);
// => false
This method returns true
if value is a function, else false
.
jQuery (deprecated since version 3.3) Reference
$.isFunction(functionName);
AngularJS Reference
angular.isFunction(value);
Lodash Reference
_.isFunction(value);
Underscore Reference
_.isFunction(object);
Node.js deprecated since v4.0.0 Reference
var util = require('util');
util.isFunction(object);
I found that when testing native browser functions in IE8, using toString
, instanceof
, and typeof
did not work. Here is a method that works fine in IE8 (as far as I know):
function isFn(f){
return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);
Alternatively, you can check for native functions using:
"getElementById" in document
Though, I have read somewhere that this will not always work in IE7 and below.
The solution as some previous answers has shown is to use typeof. the following is a code snippet In NodeJs,
function startx() {
console.log("startx function called.");
}
var fct= {};
fct["/startx"] = startx;
if (typeof fct[/startx] === 'function') { //check if function then execute it
fct[/startx]();
}
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