W3docs

How to Check if Function Exists in JavaScript

In this tutorial, you will read and learn information about the two methods of checking whether a function exists in JavaScript or it has not been defined.

There are times when you get an error while calling a function that has not been defined. Here, we suggest two methods to check if the function exists.

The typeof Method

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

Javascript typeof operator

if (typeof myFunctionName === 'function') {
  myFunctionName();
}

In the given case, the typeof operator will return undefined because <kbd class="highlighted">myFunctionName()</kbd> has not been defined. So, the function call inside the IF statement won’t be executed.

If the function exists, the typeof operator will return the string “function”:

Javascript typeof operator

javascript— editable

The try...catch Method

There is also another method of try...catch statement that catches function ReferenceError errors. This approach wraps the function call inside the try block of the statement like this:

Javascript try...catch method

javascript— editable

If the function does not exist, a ReferenceError is caught.

The typeof Operator

The typeof operator gets the data type of the unevaluated operand which can be a literal or a data structure like an object, a function, or a variable. The typeof returns a string with the name of the variable type as a first parameter (object, boolean, undefined, etc.). Before ECMAScript 2015, typeof was always returned a string for any operand it was supplied with. It could never generate an error. But after the addition of let and const, using typeof on let and const variables in a block before they’re declared will generate a ReferenceError.