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 w
I have sinced moved to coffee-script and found default arguments is a nice way to solve this problem
doSomething = (arg1, arg2, callback = ()->)->
callback()
You can also do:
var noop = function(){}; // do nothing.
function save (callback){
callback = callback || noop;
.....do stuff......
};
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 $.noop
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
Simply do
if (callback) callback();
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.