Wednesday, February 23, 2022

How to Check if a Function Exists in Java Script

How to Check if a Function Exists in Java Script

You probably have seen the undefined error in the console when you try to call a function you have not defined in your JavaScript code. JavaScript throws this error and stops running the code.

In this article, I will teach you how to check if a function exists. This way, you can avoid any possible errors. This is a useful technique to see if a specific library or API is available in the client you're running your software on.

JavaScript has a few different ways to see if a function exists. I'll show you several.

Use an if Conditional Statement

One way to check if a function is defined is to test it with an if statement. The trick is to test the function as a method of the window object. 

So, if you want to test for aFunctionName, just use:

The code in the brackets will execute if the function is defined. If instead you just test the function without using the window object, for example as if(aFunctionName),  JavaScript will throw a ReferenceErorr if the function doesn't exist.

Let us consider the following example that checks for the existence of two functions; one which exists while the other function does not exist.

The above code snippet will output this:

This worked great for our example, but a problem with that approach is that we aren't checking if the named object is actually a function. In fact, any variable with the same name would fool our test into thinking the function is defined.

The typeof Operator 

Alternatively, we can use the typeof operator. This operator will check whether the the name of the declared function exists and whether it is a function and not some other type of object or primitive.

In the example above, we test if nameOfFunction exists and if it does we run it.

Use a try…catch Block

The try…catch block handles errors that are likely to occur within that block. We will use this method to handle the undefined error we expect JavaScript to throw when we call a function that we have not defined.

How the try...catch Statement Works

We run the function inside the try block. If it doesn't exist an exception will be thrown and will be handled by the catch block.

Here's an example:

If testFunction is not defined, this will output the following message to the console.

This is what we would see without a try...catch block as well, but in this case our code will continue to run below the catch block.

Conclusion 

This article has covered three main methods to check whether a function exists in JavaScript before we call it. These are; the use of an if conditional statement, the use of a typeof operator, and finally, the try...catch statement. We have also used examples to explain how JavaScript can implement these methods to check whether a function exists or not. I hope this concept is more clear to you now!. 


No comments:

Post a Comment