javascript: optional first argument in function

You have to decide as which parameter you want to treat a single argument. You cannot treat it as both, content and options.

I see two possibilities:

  1. Either change the order of your arguments, i.e. function(options, content)
  2. Check whether options is defined:

    function(content, options) {
        if(typeof options === "undefined") {
            options = content;
            content = null;
        }
        //action
    }
    

    But then you have to document properly, what happens if you only pass one argument to the function, as this is not immediately clear by looking at the signature.


Like this:

my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both

With ES6:

function test(a, b = 3) {
   console.log(a, b);
}

test(1);      // Output: 1 3
test(1, 2);   // Output: 1 2

my_function = function(hash) { /* use hash.options and hash.content */ };

and then call:

my_function ({ options: options });
my_function ({ options: options, content: content });

Tags:

Javascript