Skip to main content

Verify calling Javascript function available to avoid runtime errors

Do you want to verify whether a Javascript function exists before calling it to avoid runtime errors? With Javascript we used to call Javascript functions. But sometimes our Javascript code tend to throw runtime errors and showing then on the browser. For this there can be several reasons including; incorrect function names or invalid .js file names causing some functions not loaded into your web page.

Javascript has the ability to check this. For that we can use the typeof keyword, and check whether that is of 'function' type or not.

Generally we will be calling a Javascript function without checking whether it exists. Following code shows how we would call a function.

function callClient(){
myTestFunction();
}

If the function named myTestFunction() is not available, the browser will show an error message at runtime. But we can check whether this method is available even before calling it, avoiding the errors. Following code snippet checks the existence before calling a function.

function callClient(){
if (typeof myTestFunction == 'function') {
myTestFunction();
} else {
alert("myTestFunction function not available");
}
}

In the above example, it checks the availability of the required function "myTestFunction" before calling it, and call it only if it exists. This will improve the user experience by avoiding unexpected error messages from the user.

Comments

  1. This's what I looked for.
    Thanks.

    ReplyDelete
  2. Always welcome and if you need any further help on Javascript please let us know.

    ReplyDelete
  3. Thank you so much :D

    ReplyDelete

Post a Comment

We appreciate your opinions, suggestions and criticism.

Popular posts from this blog

Web Services with Apache Axis 1.4 Tutorial: server and client sides

Java Sorting: Comparator vs Comparable Tutorial

Creative Commons License Digizol by Kamal Mettananda is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License .
URL of this page must be supplied in attribution
© 2004-2017