How to Check if Function Exists in JavaScript

JavaScript is a versatile programming language that can be used for various purposes, ranging from simple web page enhancements to complex applications.

One of the common problems faced by developers when working with JavaScript is checking if a function exists.

In this tutorial, we will look at different ways to check if a function exists in JavaScript.


typeof operator

The simplest way to check if a function exists in JavaScript is by using the typeof operator.

The typeof operator returns a string indicating the type of the operand.

For functions, it returns the string “function”.

Here’s an example:

function add(a, b) {
    return a + b;
}

if (typeof add === 'function') {
    console.log('The function exists');
} else {
    console.log('The function does not exist');
}

instanceof operator

Another way to check if a function exists in JavaScript is by using the instanceof operator.

The instanceof operator returns true if the specified object is an instance of the specified constructor.

Here’s an example:

function add(a, b) {
    return a + b;
}

if (add instanceof Function) {
    console.log('The function exists');
} else {
    console.log('The function does not exist');
}

try…catch statement

A third way to check if a function exists in JavaScript is by using a try…catch statement.

If a function does not exist, a ReferenceError will be thrown.

We can catch this error and return false, indicating that the function does not exist.

Here’s an example:

function add(a, b) {
    return a + b;
}

try {
    if (typeof add === 'function') {
        console.log('The function exists');
    }
} catch (e) {
    console.log('The function does not exist');
}

Conclusion

In this tutorial, we have looked at three ways to check if a function exists in JavaScript.

The typeof operator, the instanceof operator, and the try…catch statement can all be used to determine if a function exists in JavaScript.

Depending on the situation, any of these methods can be used to solve the problem of checking if a function exists.