Write a JavaScript Program to Check If a Variable is of Function Type

In JavaScript, variables can hold different types of data such as numbers, strings, objects, and functions.

As a JavaScript programmer, it is important to know how to check if a variable is of function type.

In this tutorial, we will explore a simple JavaScript program that can help you determine whether a variable is a function or not.

To check if a variable is of function type, we can use the typeof operator in JavaScript.

The typeof operator returns a string that represents the data type of the variable. For example, if we use typeof operator on a number, it will return “number”, if we use it on a string, it will return “string”, and so on.

Let’s look at an example program to check if a variable is of function type:

function myFunction() {
  console.log("Hello World!");
}

var myVariable = myFunction;

if (typeof myVariable === "function") {
  console.log("myVariable is a function!");
} else {
  console.log("myVariable is not a function!");
}

In the example program above, we have defined a function called myFunction(), and assigned it to a variable called myVariable.

We then use the typeof operator to check if the myVariable is of function type. If the typeof operator returns “function”, then we know that the variable is a function, and we log the message “myVariable is a function!”.

If the typeof operator returns any other value, then we know that the variable is not a function, and we log the message “myVariable is not a function!”.

You can also use the instanceof operator to check if a variable is of function type.

The instanceof operator returns a boolean value that indicates whether an object is an instance of a particular class or not.

In JavaScript, functions are objects, so we can use the instanceof operator to check if a variable is of function type. Here’s an example:

function myFunction() {
  console.log("Hello World!");
}

var myVariable = myFunction;

if (myVariable instanceof Function) {
  console.log("myVariable is a function!");
} else {
  console.log("myVariable is not a function!");
}

In this example, we use the instanceof operator to check if the myVariable is an instance of the Function class.

If myVariable is an instance of the Function class, then we know that it is a function, and we log the message “myVariable is a function!”.

If myVariable is not an instance of the Function class, then we know that it is not a function, and we log the message “myVariable is not a function!”.

In conclusion, checking if a variable is of function type in JavaScript is easy using the typeof operator or the instanceof operator.

As a JavaScript programmer, it is important to know how to check the data type of a variable, so that you can write reliable and error-free code.