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
  • stackoverflow.com/q/5999998 Commented Oct 24, 2012 at 16:47
  • 1
    Worth mentioning that the accepted/best answer here is simpler than the referenced question, as this is just for node ( no compatibility issues ) Commented Aug 8, 2016 at 23:52

4 Answers 4

48
if (typeof variable === 'function') {
    // do something
}
Sign up to request clarification or add additional context in comments.

1 Comment

typeof class A {} === "function" is true.
6

You can use the instanceof operator.

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

It also respects prototypal inheritance.

Comments

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 Comment

I wouldn't use underscore for this case, given that the _.isFunction function is just typeof obj == 'function' || false - github.com/jashkenas/underscore/blob/…
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:)!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.