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,490
  • 1
  • 25
  • 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).

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
Pavlo
  • 43,301
  • 14
  • 77
  • 113
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,847
  • 2
  • 15
  • 32
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

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • 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
  • 19,374
  • 4
  • 49
  • 50