JavaScript: Optional Callback?
I have coded a function, that has 3 arguments, one of them is a callback function. How do I make the callback an optional argument without having to code another function without t
Solution 1:
Ensure the callback is a function, and then invoke it.
function myFunction(arg1, arg2, callback){
// do something
typeof callback == "function" && callback();
}
If you want more control over invoking it, use call()
, apply()
, bind()
(whatever achieves your goal).
Solution 2:
Simple, just check if callback is defined before you call it.
function myFunction(arg1, arg2, callback){
// do something
if (callback) {
callback();
}
}
Post a Comment for "JavaScript: Optional Callback?"