How to check if a function exists in JavaScript

Learn how to avoid an error caused by calling a non-existent function by checking it first.

Posted on March 27, 2021


An error caused by calling a non-existent function will cause JavaScript to throw an undefined error and stop running your code. To prevent the error, you can first check if a function exists in your current JavaScript environment by using a combination of an if statement and the typeof operator on the function you want to call.

Only when the typeof returns "function" will you call that function to execute it. Let’s look at the following example:

function printMessage(){
  console.log("Hello World!");
}

if(typeof printMessage === "function"){
  printMessage();
}

When the type of printMessage is anything other than "function", you don’t call the function.

Handling non-existent function with try..catch block

Alternatively, you can also use a try..catch block to handle the error when a non-existent function is called:

try {
  printMessage();
} catch (err) {
  console.log(err); // Error: "printMessage is not defined"
}

// code below won't be executed without try..catch block

console.log("abc...");
console.log("...The script execution continues...");
console.log("...even when there's an error");

Without the try..catch block, the console logs above won’t be executed by JavaScript. You can use the techniques above to check if a JavaScript function exists before calling it.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more