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
}
user1091856
  • 3,032
  • 6
  • 31
  • 42

2 Answers2

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

alex
  • 479,566
  • 201
  • 878
  • 984
  • 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. – Evan Trimboli Aug 30 '12 at 07:18
  • @Evan you prefer to call a variable's value that may not be a function? – alex Aug 30 '12 at 12:30
  • 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. – Evan Trimboli Aug 30 '12 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. – webdesserts Nov 23 '13 at 20:22
  • @mcmullins I usually do that. This question however asks for an optional callback. It wouldn't be too optional if omitting it would raise an exception. Checking its type and failing if it's not a function can be useful, but it's not as popular in JavaScript (maybe it should be?) – alex Nov 24 '13 at 11:49
  • 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. – webdesserts Nov 24 '13 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 '13 at 21:11
6

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

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

    if (callback) {
        callback();
    }
}
Lucas Green
  • 3,951
  • 22
  • 27
  • 2
    Will error if they pass an object that doesn't implement `[[Call]]`. – alex Aug 30 '12 at 07: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 '14 at 11:11