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(); }; };
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With