Javascript: assigning the second optional argument without assigning the first

856 views Asked by At

I'm trying to create a function that has multiple optional arguments. I am then trying to only assign the second argument without having to also assign the first one.

function foo(bar, zar) {
  bar = bar || 5;
  zar = zar || 2;

  return bar * zar;
}

foo()      //10
foo(7)     //14
foo(7, 3)  //21
foo(zar=5) //10 <-- why is this not 25?

What is the best way to do this?

3

There are 3 answers

4
Luka Čelebić On

Use void 0 instead of the arguments you don't want to supply.

For example: foo(void 0,zar=5);

Any unfilled argument will be undefined.

You cannot pass the second parameter without passing the first, but you can pass undefined. In the function, you can check for undefined and replace with a default value.

Alternately, you can use an object argument to imitate keyword arguments.

0
tylerwgrass On

You could pass undefined for whatever parameters you would want to use as defaults.

foo(undefined, 5);

Also, if you are free to use ES6, you can simplify your function a little and declare your optional parameters like so:

function foo(bar = 5, zar = 2) { }

0
4castle On

IMHO, the easiest way to handle this kind of situation is to instead use an object for the parameter, with default field values via the ES6 syntax.

function foo({ bar = 5, zar = 2 } = {}) {
  console.log(bar * zar);
}

foo() //10
foo({ bar: 7 }) //14
foo({ bar: 7, zar: 3 }) //21
foo({ zar: 5 }) //25

For reference, see: Default parameters and Object destructuring.