In JavaScript, you can use the `typeof` operator to check the type of a variable. To specifically check if a variable is a function, you can compare the result of `typeof` with the string `"function"`. Here's an example:
function myFunction() {// Function body}let myVariable = 42;let anotherVariable = "Hello, world!";console.log(typeof myFunction === "function"); // Outputs: trueconsole.log(typeof myVariable === "function"); // Outputs: falseconsole.log(typeof anotherVariable === "function"); // Outputs: false
In this example, `typeof myFunction === "function"` returns `true` because `myFunction` is indeed a function. On the other hand, `typeof myVariable === "function"` and `typeof anotherVariable === "function"` return `false` because `myVariable` is a number, and `anotherVariable` is a string.
It's important to note that this method of checking for a function only works when the variable is explicitly declared as a function. If you have a function expression assigned to a variable, it will still return `"function"`:
let functionExpression = function() {// Function body};console.log(typeof functionExpression === "function"); // Outputs: falseconsole.log(typeof functionExpression === "object"); // Outputs: true
In this case, `typeof functionExpression === "function"` returns `false`. If you need to check whether a variable is callable as a function, you might consider additional checks or use other methods, such as the `typeof` operator combined with a function call:
console.log(typeof functionExpression === "function" || typeof functionExpression === "object" && typeof functionExpression.call === "function"); // Outputs: true
This additional check ensures that the variable is not only of type `"function"` but also has a `call` method, making it callable as a function.
Social Plugin