How To Check If Variable Is Of Function Type Using JavaScript?

how to check if Variable is of Function Type using JavaScript

Data type handling is a common task in any programming language, and JavaScript is no exception. In this article, let’s see detailed examples of how the typeof(), instanceof() operators work and learn how to check if variable is of function type using JavaScript.

Check if variable is of function type using JavaScript

Method 1: Use typeof() operator

The simplest method to check if the variable is of function type using JavaScript is using the typeof() operator.

The typeof() function is used to determine the data type of a variable in JavaScript. But for a function, technically, JavaScript will treat it as an object. Let’s see the example below.

Syntax: 

typeof operand

Parameters:

  • operand: In this case, the operand is a value and a variable.

Code sample:

function add(a, b) {
  return a + b;
}

let type = typeof add;
console.log("Type of add is ", type);

Output:

Type of add is function

Even if it’s an arrow function, the typeof function still returns the data type “function”.

Code sample:

let sum = (a, b) => a + b;

let type = typeof sum;
console.log(type);

Output:

function

Some small notes when using the function typeof():

As for the syntax, you already know through the examples I showed you (typeof operand). But be aware that when the operand is an operator, you must use the below syntax.

Syntax: 

typeof(operand)

Parameters:

  • operand: In this case, operands are operators. It must be in parentheses.

Code sample:

let type = typeof (100 + 100);
console.log(type);

Output:

number

Method 2: Use instanceof() operator

Another solution is using the instanceof() operator.

The instanceof operator is used to check if an object is an object of a specified class. This operator returns true or false.

Syntax: 

anObject instanceof AClass;

let result = anObject instanceof AClass;

Parameters:

  • In the left of instanceof is a object.
  • In the rigth of instanceof is a class.

Code Example:

let example = function(){/* A set of statements */};
  
function testing(x) {      
    if(x instanceof Function) {
        console.log("Variable is of function type");
    }
    else {
        console.log("Variable is not of function type");
    }
}
  
testing(example);

Output:

Variable is of function type

Summary

So through this article, you have not only used the typeof() function to check if variable is of function type using JavaScript, but you can also use it proficiently for many other cases of yours. Thank you for following this post! Take care!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *