Check if a JavaScript function is defined.

In this tutorial, I will show you how to check if a JavaScript function is defined or not. This can be useful if you do not want to call a function unless you are 100% sure that it exists.

For example: A particular function exists in an external library and you do not want your code to throw a ReferenceError if that library hasn’t been included properly.

Take a look at the following JavaScript snippet:

//Calling a function that isn't defined.
bad_function_call();

In the code above, I am calling a function that doesn’t exist. As a result, the following error will be thrown in the developer console:

Uncaught ReferenceError: bad_function_call is not defined
at file.php:2

The error above is basically telling us that our code has attempted to reference a function that hasn’t been defined. As a result, the rest of our JavaScript code will not be executed.

Check if a JavaScript function exists before calling it.

To check if a particular function name has been defined, you can use JavaScript’s typeof operator:

//Use the typeof operator to check if a JS function exists.
if(typeof bad_function_call === "function"){
    bad_function_call();
}

In our case, the typeof operator will return the string “undefined” because bad_function_call has not been defined. As a result, the function call inside the IF statement will not be executed.

If the function in question does exist, then the typeof operator will return the string “function”:

//Test function.
function test(){
    alert('Hi!');
}

//Call the function above if it exists.
if(typeof test === "function"){
    test();
}

If you run the JavaScript example above, you will see that an alert box with the string “Hi!” appears.

Catching function ReferenceError errors with a try / catch statement.

Note that another approach is to wrap your function call inside the try block of a try / catch statement like so:

try{
    bad_function_call();
} catch(error) {
    console.log(error);
}

If the function in question does not exist, the error is caught and logged to the console.

Hopefully, you found this guide useful!