3

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?

sertsedat
  • 3,320
  • 1
  • 23
  • 45

4 Answers4

2

The common convention for ES2015 is to pass an object as a single argument, assign default values for it's properties and than use destructuring inside the function:

const DoSomething = ({ arg1 = false, notify = false } = {}) => {
  /* DO SOMETHING */
};

DoSomething({ notify: true }); // In the function: arg1=false, notify= true

You can call this function without any arguments at all, i.e. DoSomething(), but this requires default value for the object (= {} at the end of the arguments list).

Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
Pavlo
  • 40,007
  • 13
  • 74
  • 108
1

You can achieve something similar by passing an object:

function DoSomething(param) {
  var arg1 = param.arg1 !== undefined ? param.arg1 : false,
      notify = param.notify !== undefined ? param.notify : false;

  console.log('arg1 = ' + arg1 + ', notify = ' + notify);
}

DoSomething({ notify: true });
Arnauld
  • 5,485
  • 2
  • 14
  • 28
1

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

Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
  • 1
    Never knew about the `Object.assign` method! It seems like something that popped up in numerous frameworks, usually as "mixin". That's handy. – Katana314 Jul 27 '16 at 17:37
0

Pass object as argument:

function DoSomething(obj){

 if (obj.hasOwnProperty('arg1')){

  //arg1 isset
 }

 if (obj.hasOwnProperty('notify')){

  //notify isset
 }

}

usage:

DoSomething({
 notify:false
});
Maciej Sikora
  • 17,646
  • 4
  • 41
  • 44