3

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 the callback argument?

function myFunction(arg1, arg2, callback){
    // do something

    // callback() if it has been passed
}
0

2 Answers 2

21

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).

7
  • The functionality is fine, but from a stylistic point I find the typeof/invocation in a single line to be ugly. Much prefer the style of Mythril's answer. Aug 30, 2012 at 7:18
  • 2
    No, I just don't like the way you've written it on a single line. To clarify, if (typeof callback == 'function') { callback(); }, but formatted correctly. Aug 30, 2012 at 13:21
  • 1
    @alex Wouldn't you want this to error out? As a user of someone else's interface, I would want to know if the value I inserted was not the expected value, rather that just having it ignored. Nov 23, 2013 at 20:22
  • 1
    @alex When I think of an optional callback I think of a function where both say('hello') and say('hello', callback) work. I would still expect say('hello', 'world') to error out. Otherwise I'll never know that isn't what the function expects. if (cb) cb(); is simpler and provides an error when the callback's type is wrong. typeof would be more useful if you were providing your own custom error, which in your case, you're not. Nov 24, 2013 at 18:08
  • 1
    @mcmullins Ah right, I see what you're getting at now. I agree. Hopefully people aren't fishing around with different arguments to infer a function's argument signature though :)
    – alex
    Nov 24, 2013 at 21:11
7

Simple, just check if callback is defined before you call it.

function myFunction(arg1, arg2, callback){
    // do something

    if (callback) {
        callback();
    }
}
2
  • 2
    Will error if they pass an object that doesn't implement [[Call]].
    – alex
    Aug 30, 2012 at 7:17
  • 1
    It is good style to force errors, that way the implementor is not misguided into thinking his callback was infact accepted
    – ninja123
    Mar 31, 2014 at 11:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.