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();
};
};
ECMAScript 6
Rather than make the callback optional, just assign a default and call it no matter what
When used
Such a style is called continuation-passing style. Here's a real example,
combinations
, that generates all possible combinations of an Array inputBecause
combinations
is defined in continuation-passing style, the above call is effectively the sameWe can also pass a custom continuation that does something else with the result
Continuation-passing style can be used with surprisingly elegant results
If the criteria for running the callback is that whether its defined or not, then you're fine. Also, I suggest to check if its really a function in addition.
Simply do
I prefer to call the callback if supplied, no matter what type it is. Don't let it fail silently, so the implementor knows he passed in an incorrect argument and can fix it.
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 functionA valid function is based on the Function prototype, use:
to be sure the callback is a function