Detect if a function exists in Javascript
It is comman practice we call a call back functions in our javascript application ,we know that calling a non existed javascript function triggers a error. In order to overcome these kind of errors we must check that function exists and call only if that exists.
Generelly every function has scope in window object of browsers unless classes,objects instances.
Example:
function myfunction (){
var foo;
}
now this function defination can be collected in in window scope.
We check if this function defined using a simple IF condition as below.
if(window.myfunction){
}else{
}
Above will return true even it is function or a variable, so we have confine the condition to exactly is it function or not.
as below
if( typeof myfunction==="function"){
}else{
}
Javascript function is also a Object ,we can check for its instance kind is Base function prototype.
if( myfunction instanceof Function){
}else {
}
Above methods works if only we get perticular function know, in our dynamic applications we have to check at run time and we don’t know exactly the name of the function. So we make a small function that will do for us.
function function_exists (function_name) { if (typeof function_name === 'string'){ return (typeof window[function_name] === 'function'); } else{ return (function_name instanceof Function); } } |
In above function the parameter can be string or a direct function reference. first we check if given parameter is string , then we check the function in the window scope.if given paramenter is direct function reference we check that it is instace of function prototype.

