Check if a Variable is of Function Type using JavaScript
A function in JavaScript is a set of statements used to perform a specific task. A function can be either a named one or an anonymous one. The set of statements inside a function is executed when the function is invoked or called.
let gfg = function(){/* A set of statements */};
Here, an anonymous function is assigned to the variable named as 'gfg'. There are various methods to check the variable is of function type or not. Some of them are discussed below:
Table of Content
Using instanceof operator
The instanceof operator checks the type of an object at run time. It return a corresponding boolean value, i.e, either true or false to indicate if the object is of a particular type or not.
Example: This example uses instanceof operator to check a variable is of function type or not.
// Declare a variable and initialize it
// with anonymous function
let gfg = function () {/* A set of statements */ };
// Function to check a variable is of
// function type or not
function testing(x) {
if (x instanceof Function) {
console.log("Variable is of function type");
}
else {
console.log("Variable is not of function type");
}
}
// Function call
testing(gfg);
Output
Variable is of function type
Using Strict Equal (===) operator
In JavaScript, ‘===’ Operator is used to check whether two entities are of equal values as well as of equal type provides a boolean result. In this example, we use the '===' operator. This operator, called the Strict Equal operator, checks if the operands are of the same type.
Example: This example uses === operator to check a variable is of function type or not.
// Declare a variable and initialize it
// with anonymous function
let gfg = function () {/* A set of statements */ };
// Function to check a variable is of
// function type or not
function testing(x) {
if (typeof x === "function") {
console.log("Variable is of function type");
}
else {
console.log("Variable is not of function type");
}
}
// Function call
testing(gfg);
Output
Variable is of function type
Using object.prototype.toString
This method uses object.prototype.toString. Every object has a toString() method, which is called implicitly when a value of String type is expected. If the toString() method is not overridden, by default it returns '[object type]' where 'type' is the object type.
Example: This example uses object.prototype.toString operator to check a variable is of function type or not.
// Declare a variable and initialize it with an anonymous function
let gfg = function () {
// A set of statements
};
// Function to check if a variable is of function type or not
function testing(x) {
if (typeof x === 'function') {
console.log("Variable is of function type");
} else {
console.log("Variable is not of function type");
}
}
// Function call
testing(gfg);
Output
Variable is of function type