javascript tutorial - [Solved-5 Solutions] How can we check if a javascript variable is function type ? - javascript - java script - javascript array



Problem:

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

var a = function(){/* Statements */};
click below button to copy the code. By JavaScript tutorial team

We 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);
click below button to copy the code. By JavaScript tutorial team

How can we check if the variable 'a' is of type function in the way defined above?

Solution 1:

  • 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) {
 var getType = {};
 return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
click below button to copy the code. By JavaScript tutorial team

Solution 2:

	if (typeof v === "function") {
// do something
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

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

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

click below button to copy the code. By JavaScript tutorial team

Solution 4:

If we use jquery we can use the isFunction:

$.isFunction(functionName);
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Try instanceof: 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

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - How can we check if a javascript variable is function type ?