check if it is a function javascript

How to check if it is a function in JavaScript

If you are a JavaScript developer, it is essential to know how to identify whether a variable is a function or not. There are various ways to check if a variable is a function, and we will discuss some of them here.

Using the typeof operator

The easiest and most common way to check if a variable is a function is by using the typeof operator. It returns the type of the operand, and if the operand is a function, it will return "function". Here is an example:


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

console.log(typeof myFunction); // Output: "function"

Using the instanceof operator

You can also use the instanceof operator to check if a variable is a function. It checks if an object is an instance of a particular class, and since functions are objects in JavaScript, you can use this operator to check if a variable is a function. Here is an example:


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

console.log(myFunction instanceof Function); // Output: true

Using the Object.prototype.toString() method

The Object.prototype.toString() method returns the type of an object as a string. You can use this method to check if a variable is a function by calling it on the variable and checking if the returned string contains the word "function". Here is an example:


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

console.log(Object.prototype.toString.call(myFunction)); // Output: "[object Function]"

These are some of the most common ways to check if a variable is a function in JavaScript. Remember that functions are objects in JavaScript, so you can use any method that checks if a variable is an object to check if it is a function.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe