21

Possible Duplicate:
How can I check if a javascript variable is function type?

How i check if a variable is a function for Array exist Array.isArray() but Function.isFunction dos'nt exist

2

4 Answers 4

48
if (typeof variable === 'function') {
    // do something
}
1
6

You can use the instanceof operator.

var fn = function() {};
var result = fn instanceof Function; // result will be true

It also respects prototypal inheritance.

4

Underscore.js is a library that has a lot of useful helpers, like the one you're looking for.

http://underscorejs.org/

_ = require('underscore');

var aFunction = function() { };
var notFunction = 'Not a function';

_.isFunction(aFunction); // true
_.isFunction(notFunction); // false
1
1
var fn = function() {},
    toString = Object.prototype.toString;

first way:

if( toString.call( function(){} ) === '[object Function]' ) {
    //if is Function do something...
}

second way:

if( fn.constructor.name = 'Function' ) {
    //if is Function do something...
}

Hope it helps cheers:)!

Not the answer you're looking for? Browse other questions tagged or ask your own question.