Check if a variable is of function type

Javascript

Javascript Problem Overview


Suppose I have any variable, which is defined as follows:

var a = function() {/* Statements */};

I want a function which checks if the type of the variable is function-like. i.e. :

function foo(v) {if (v is function type?) {/* do something */}};
foo(a);

How can I check if the variable a is of type Function in the way defined above?

Javascript Solutions


Solution 1 - Javascript

if (typeof v === 'function') {
    // do something
}

Solution 2 - Javascript

Sure underscore's way is more efficient, but the best way to check, when efficiency isn't an issue, is written on underscore's page linked by @Paul Rosania.

Inspired by underscore, the final isFunction function is as follows:

function isFunction(functionToCheck) {
 return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

Note: This solution doesn't work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.

Solution 3 - Javascript

There are several ways so I will summarize them all

  1. Best way is:

    function foo(v) {if (v instanceof Function) {/* do something */} };

    Most performant (no string comparison) and elegant solution - the instanceof operator has been supported in browsers for a very long time, so don't worry - it will work in IE 6.
  2. Next best way is:

    function foo(v) {if (typeof v === "function") {/* do something */} };

    disadvantage of typeof is that it is susceptible to silent failure, bad, so if you have a typo (e.g. "finction") - in this case the if will just return false and you won't know you have an error until later in your code
  3. The next best way is:

    function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }

    This has no advantage over solution #1 or #2 but is a lot less readable. An improved version of this is

    function isFunction(x) { return Object.prototype.toString.call(x) == '[object Function]'; }

    but still lot less semantic than solution #1

Solution 4 - Javascript

Underscore.js uses a more elaborate but highly performant test:

_.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
};

See: https://jsben.ch/B6h73

EDIT: updated tests suggest that typeof might be faster, see https://jsben.ch/B6h73

Solution 5 - Javascript

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);

Solution 6 - Javascript

@grandecomplex: There's a fair amount of verbosity to your solution. It would be much clearer if written like this:

function isFunction(x) {
  return Object.prototype.toString.call(x) == '[object Function]';
}

Solution 7 - Javascript

var foo = function(){};
if (typeof foo === "function") {
  alert("is function")
}

Solution 8 - Javascript

Something with more browser support and also include async functions could be:

const isFunction = value => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function);

and then test it like:

isFunction(isFunction); //true
isFunction(function(){}); //true
isFunction(()=> {}); //true
isFunction(()=> {return 1}); //true
isFunction(async function asyncFunction(){}); //true
isFunction(Array); //true
isFunction(Date); //true
isFunction(Object); //true
isFunction(Number); //true
isFunction(String); //true
isFunction(Symbol); //true
isFunction({}); //false
isFunction([]); //false
isFunction("function"); //false
isFunction(true); //false
isFunction(1); //false
isFunction("Alireza Dezfoolian"); //false





Solution 9 - Javascript

Try the instanceof operator: it seems that all functions inherit from the Function class:

// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();

// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false

Solution 10 - Javascript

An other simply way:

var fn = function () {}
if (fn.constructor === Function) {
  // true
} else {
  // false
}

Solution 11 - Javascript

For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.

Next code contains only pure and pointfree functions:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);

As of ES2017, async functions are available, so we can check against them as well:

const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

And then combine them together:

const isFunction = R.either(isSyncFunction, isAsyncFunction);

Of course, function should be protected against null and undefined values, so to make it "safe":

const safeIsFunction = R.unless(R.isNil, isFunction);

And, complete snippet to sum up:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

const isFunction = R.either(isSyncFunction, isAsyncFunction);

const safeIsFunction = R.unless(R.isNil, isFunction);

// ---

console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));

However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.

Solution 12 - Javascript

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.

Solution 13 - Javascript

The below seems to work for me as well (tested from node.js):

var isFunction = function(o) {
     return Function.prototype.isPrototypeOf(o);
};

console.log(isFunction(function(){})); // true
console.log(isFunction({})); // false

Solution 14 - Javascript

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.

Solution 15 - Javascript

I think you can just define a flag on the Function prototype and check if the instance you want to test inherited that

define a flag:

Function.prototype.isFunction = true; 

and then check if it exist

var foo = function(){};
foo.isFunction; // will return true

The downside is that another prototype can define the same flag and then it's worthless, but if you have full control over the included modules it is the easiest way

Solution 16 - Javascript

you should use typeOf operator in js.

var a=function(){
    alert("fun a");
}
alert(typeof a);// alerts "function"

Solution 17 - Javascript

Since node v0.11 you can use the standard util function :

var util = require('util');
util.isFunction('foo');

Solution 18 - Javascript

if you are looking for a simple solution:

 function isFunction(value) {
   return value instanceof Function
}

Solution 19 - Javascript

Becareful about this :

typeof Object === "function" // true.
typeof Array  === "function" // true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJesufer VnView Question on Stackoverflow
Solution 1 - JavascriptselbieView Answer on Stackoverflow
Solution 2 - JavascriptAlex GrandeView Answer on Stackoverflow
Solution 3 - JavascriptdalimianView Answer on Stackoverflow
Solution 4 - JavascriptPaul RosaniaView Answer on Stackoverflow
Solution 5 - JavascriptCesar LoachaminView Answer on Stackoverflow
Solution 6 - JavascriptdandeanView Answer on Stackoverflow
Solution 7 - JavascriptwscView Answer on Stackoverflow
Solution 8 - JavascriptAlirezaView Answer on Stackoverflow
Solution 9 - Javascriptuser1176126View Answer on Stackoverflow
Solution 10 - JavascriptGuillaumeLView Answer on Stackoverflow
Solution 11 - JavascriptDamaged OrganicView Answer on Stackoverflow
Solution 12 - JavascriptsaetaView Answer on Stackoverflow
Solution 13 - JavascriptMarcus Junius BrutusView Answer on Stackoverflow
Solution 14 - JavascriptAzmisovView Answer on Stackoverflow
Solution 15 - JavascriptDanny MorView Answer on Stackoverflow
Solution 16 - JavascriptRajesh PaulView Answer on Stackoverflow
Solution 17 - JavascriptmoklickView Answer on Stackoverflow
Solution 18 - JavascriptDe BonheurView Answer on Stackoverflow
Solution 19 - JavascriptYassine CHABLIView Answer on Stackoverflow