How to check if a JavaScript function exists or not?

In many times we need to create functions in JavaScript. After we create a function it will not be used until we call it. But what happened if we call a function, but we forget to create the function or we have not included the JavaScript file that contains the function. We are calling a JavaScript function which doesn’t exist and cases error in the console log. What can we do to remove the error?

Locate the Geo-position of a visitor in JavaScript

Show live preview of HTML textarea with JavaScript

In this situation, we can do one thing. Before we calling the function we have to check if the function exists or not and after that if we find it exists then call it, otherwise the function will not be called.

JavaScript code to check if a function exists

Now we are going to see the javaScript code. First, create our javaScript function:

function myFunction()
	alert('This is coming from the JavaScript function');

Now below is our code to check if myFunction() JavaScript function exists or not:

if (typeof myFunction == 'function') { 

Now if our function exists, then it will return the alert message “This is coming from the JavaScript function”. But if the function doesn’t exist then we will not see the alert message as the function does not exists that contains the alert message.

Play/Pause Button For HTML5 Video Using JavaScript

So we have seen hat it is so simple to check if a function exists before calling it and it is always a good idea to avoid the error message of console log.

Leave a Reply

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