JavaScript has the ability to check the existence of a function.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.
0 Response to "Verify calling JavaScript function available to avoid runtime errors"
Post a Comment