Monday, June 3, 2024
57
rated 0 times [  58] [ 1]  / answers: 1 / hits: 67990  / 13 Years ago, fri, july 22, 2011, 12:00:00

I have some functions which occasionally (not always) will receive a callback and run it. Is checking if the callback is defined/function a good style or is there a better way?



Example:



function save (callback){
.....do stuff......
if(typeof callback !== 'undefined'){
callback();
};
};

More From » coding-style

 Answers
15

I personally prefer



typeof callback === 'function' && callback();



The typeof command is dodgy however and should only be used for undefined and function



The problems with the typeof !== undefined is that the user might pass in a value that is defined and not a function


[#91054] Thursday, July 21, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gonzaloulyssess

Total Points: 225
Total Questions: 114
Total Answers: 112

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
gonzaloulyssess questions
Sat, Dec 11, 21, 00:00, 3 Years ago
Wed, Mar 3, 21, 00:00, 3 Years ago
Wed, Oct 21, 20, 00:00, 4 Years ago
;