In JavaScript, there are several ways to check whether a variable is a function.
Here are three common ways:
Using the typeof
operator:
function myFunc() {
console.log("Hello World");
}
typeof myFunc === "function"; // true
The typeof
operator returns a string indicating the type of the operand. When applied to a function, typeof
returns the string “function”.
Using the instanceof
operator:
function myFunc() {
console.log("Hello World");
}
myFunc instanceof Function; // true
The instanceof
operator checks whether an object belongs to a specific class. In this case, we’re checking whether myFunc
belongs to the Function
class.
Using Object.prototype.toString.call()
:
function myFunc() {
console.log("Hello World");
}
Object.prototype.toString.call(myFunc) === "[object Function]"; // true
Object.prototype.toString.call()
returns a string representation of the object’s type. When called on a function, it returns the string “[object Function]“.
All of these methods should return true
if the variable is a function. It’s worth noting that none of these methods will return true
for function expressions that have not been assigned to a variable.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.