How to check if a function exists in JavaScript

Posted on Mar 27, 2021

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

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"){

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 {
} catch (err) {
  console.log(err); // Error: "printMessage is not defined"

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

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.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.