How to Check if Function Exists in JavaScript

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 typof Method

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

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

In the given case, the typeof operator will return undefined because myFunctionName() has not been defined. So, the function call inside the IF statement won’t be executed.

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

function test() {
  console.log('Welcome to W3Docs');
}
//Call the function above if it exists.
if (typeof test === "function") {
  test();
}

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:

try {
  eval('a x b');
} catch (err) {
  console.log(err.name); // "SyntaxError"
  console.log(err.message); // "Unexpected identifier"
}

If the function does not exist, the error occurs.

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 Statements/const using typeof on let and const variables in a block before they’re declared will generate a ReferenceError.


Do you find this helpful?

Related articles