How to check if a JavaScript variable is a function or not.

This is a simple guide on how to check if a JavaScript variable is a function or not. As you probably already know, JavaScript allows you to create and assign functions to variables. This makes it possible to pass functions as parameters to other functions.

Let’s jump right in and take a look at the following code snippet, which includes a custom function that checks to see whether a given variable is a function or not:

//Create a JS function and assign it to a variable
//called "func"
var func = function(){
    //Print to the browser console.
    console.log('Hello! I am a function!');
};

//Create a simple JS string for example purposes.
var str = 'I am not a function!';

//Our custom function, which checks to see if a variable
//is a function or not.
function isFunction(variableToCheck){
    //If our variable is an instance of "Function"
    if (variableToCheck instanceof Function) {
        return true;
    }
    return false;
}

//Check to see if our JavaScript variable "func" is a function.
if(isFunction(func)){
    //If it is, print to console and call the function.
    console.log('func is a function!');
    func();
} else{
    console.log('func is not a function!');
}

//Check to see if our JavaScript variable "str" is a function.
if(isFunction(str)){
    //If it is, print to console and call the function.
    console.log('str is a function!');
    str();
} else{
    console.log('str is not a function!');
}

In the above example:

  1. We create two different variables – a function type variable and a string type variable.
  2. We create a custom function called isFunction, which checks to see if a JS variable is of type “function” or not. This returns TRUE or FALSE.
  3. We then test both of our variables and log the results to the console.

Best of all, the custom function above will even work in old browsers such as Internet Explorer 6!

Hopefully, you found this guide to be helpful!