Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  37] [ 4]  / answers: 1 / hits: 7241  / 10 Years ago, sun, july 27, 2014, 12:00:00

I saw many kinds of methods for checking callback function before calling.



1)



 function(callBack)    
{
...
if(callBack != null)
callBack();
}


2)



  function(callBack)    
{
...
if(typeof callBack == 'function')
callBack();
}


3)



  function(callBack)    
{
...
if(callBack !== null)
callBack();
}


4)



  function(callBack)    
{
...
if(callBack != undefined)
callBack();
}


5)



   function(callBack)    
{
...
try{
callBack();
} catch(err) {}

}


6)



   function(callBack)    
{
...
if (callBack && typeof(callBack) == function)
callBack();

}


7)



    function(callBack)    
{
...
if(callBack)
callBack();

}


8)



    function(callBack)    
{
...
if(typeof window[callBack] === 'undefined')
callBack();

}


9)



  function(callBack)    
{
...
if(callBack instanceof Function)
callBack();

}


I believe there is more...



What is the best way for checking if the given 'callBack' parameter is a function?



And why not to use the other examples.


More From » callback

 Answers
5

if (callBack != null)




Sure, why not. Notice there are still many non-function values that pass this.




if (typeof callBack == 'function')




That's exactly what you want.




if (callBack !== null)




No. Does not work when callBack is undefined.




if (callBack != undefined)




Rather not. See How to check for "undefined" in JavaScript? for why null is favoured (though equivalent).




try{ callBack(); } catch(err) {}




Uh, possibly slower and swallowing any errors in the callback. If that is what you want, you should still combine it with one of the other tests.




if (callBack && typeof(callBack) == function)




Redundant, but possibly faster than a mere typeof test. You will want to test this if you care about performance, otherwise there's hardly a reason to be so verbose.




if (callBack)




Sure, why not. Notice there are still many truthy non-function values that pass this.




if (typeof window[callBack] === 'undefined')




No. This is absolutely doing a very different thing.




if (callBack instanceof Function)




This should work for everything but some extreme edge cases, but using typeof is safer (and faster).


[#43568] Friday, July 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katelynn

Total Points: 378
Total Questions: 86
Total Answers: 108

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
;