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

Community
  • 1
  • 1
Rolando Corratge Nieves
  • 1,233
  • 2
  • 10
  • 25

4 Answers4

48
if (typeof variable === 'function') {
    // do something
}
аlex
  • 5,426
  • 1
  • 29
  • 38
paul
  • 1,201
  • 12
  • 9
6

You can use the instanceof operator.

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

It also respects prototypal inheritance.

Manu Clementz
  • 1,807
  • 12
  • 19
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
BadCanyon
  • 3,005
  • 19
  • 17
  • 1
    I wouldn't use underscore for this case, given that the _.isFunction function is just `typeof obj == 'function' || false` - https://github.com/jashkenas/underscore/blob/e944e0275abb3e1f366417ba8facb5754a7ad273/underscore.js#L1338 – tylucaskelley Aug 09 '17 at 20:32
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:)!

orustammanapov
  • 1,792
  • 5
  • 25
  • 44