javascript: optional first argument in function

Solution 1:

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.

Solution 2:

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

and then call:

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