Search code examples
javascriptparameter-passingdefault-parameters

Specifying which parameter to pass


Consider that I have a method like below, in C#.

void DoSomething(bool arg1 = false, bool notify = false)
{ /* DO SOMETHING */ }

I can specify which parameter I pass to method like this:

DoSomething(notify: true);

instead of

DoSomething(false, true);

Is it possible in Javascript?


Solution

  • It's not possible, but you can workaround it by passing objects and adding some custom code

    /**
     * This is how to document the shape of the parameter object
     * @param {boolean} [args.arg1 = false] Blah blah blah
     * @param {boolean} [args.notify = false] Blah blah blah
     */
    function doSomething(args)  {
       var defaults = {
          arg1: false,
          notify: false
       };
       args = Object.assign(defaults, args);
       console.log(args)
    }
    
    doSomething({notify: true}); // {arg1: false, notify: true}
    

    And you could generalize this

    createFuncWithDefaultArgs(defaultArgs, func) {
        return function(obj) {
            func.apply(this, Object.assign(obj, defaultArgs);
        }
    }
    
    var doSomething = createFuncWithDefaultArgs(
        {arg1: false, notify: false}, 
        function (args) {
             // args has been defaulted already
    
        }
    ); 
    

    Note that Object.assign is not supported in IE, you may need a polyfill