One of the easiest ways we can use JavaScript to check if a variable is a function is by using the JavaScript typeof Operator in an if conditional statement.

if ( typeof someVariable == "function" ){
  //The variable IS a function
}

In the code above, someVariable is the variable that we want to check to see if it is a function. typeof someVariable will return “function” if the variable is a function, and therefore the conditional statement will be true.

We can put this code in a function to make checking if a variable is a function very simple.

Here is the function:

function isFunction(variable){
  if ( typeof variable == "function" ){
    return true;
  } else {
    return false;  
  }
};

Our function simply returns true if the variable you enter is a function, and false if not.

Now let’s show some examples of this function is use:

function isFunction(variable){
  if ( typeof variable == "function" ){
    return true;
  } else {
    return false;  
  }
};

var variable1 = {name:'tom', age:25};
var variable2 = [1,2,3,4];
var variable3 = "1234";
var variable4 = ["Red","Yellow","Green","Blue"];
var variable5 = function isFunction(variable){
  if ( typeof variable == "function" ){
    return true;
  } else {
    return false;  
  }
};
var variable6 = {};

console.log(isFunction(variable1));
console.log(isFunction(variable2));
console.log(isFunction(variable3));
console.log(isFunction(variable4));
console.log(isFunction(variable5));
console.log(isFunction(variable6));

#Output:
false
false
false
false
true
false

Hopefully this article has been useful for you to learn how to use JavaScript to check if a variable is a function.

Categorized in:

JavaScript,

Last Update: March 12, 2024