How to Check If a Function Exists in JavaScript

Learn how to check if a function exists or not using the typeof operator in JavaScript.

Published Categorized as JavaScript

You may need to check if a function already exists before calling it.

To check if a function exists in JavaScript, you can use the typeof operator. The typeof operator tells you what type of the operand.

For example, if you use typeof with a function’s name and it says “function,” that’s how you know the function exists.

Here’s how to make it work:

if (typeof myFunction === 'function') { 
    // true
    console.log("The function exists.");
} else {
    // false
    console.log("The funciton does not exist.");
}

Remember, in JavaScript, a variable can be undefined which means that it has been declared but has not yet been assigned a value.

On the other hand, a variable can be undeclared which means that it has not been declared at all. If you try to access an undeclared variable, JavaScript will throw a ReferenceError.

The typeof operator treats undeclared variables as if they were declared with undefined value, so it won’t throw a ReferenceError even if the variable you are checking doesn’t exist at all.

Also, this will only check if a variable with the name myFunction exists in the current scope. If there is a function with that name in a different scope, this code won’t find it.

So make sure to check the correct scope.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *