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 got so tired of seeing that same snippet over and over I wrote this:
I've got hundred of functions doing things like
or whatever...
I'm skeptical of the whole "make sure it's function" strategy. The only legitimate values are a function or falsy. If someone passes in a non-zero number or a non-empty string, what are you going to do? How does ignoring the problem solve it?
You can also do:
It's specially useful if you happen to use the
callback
in a few places.Additionally if you are using
jQuery
, you already have a function like that, it's called $.noopIt can easilly be done with ArgueJS:
I have sinced moved to coffee-script and found default arguments is a nice way to solve this problem