0

The scenario is as follows:

function:

const fun = (a="keep this", b="change this")=>{return a + b};

How can I keep the first default parameter and override the second one? I have several functions that use many default parameters that are called in different ways, so just moving the b param to the first argument will not work. For the sake of simplicity, a would hypothetically be overridden nearly as often as b.

I found answers regarding optional parameters but none showed me how to specify parameter while retaining defaults before said parameter.

I tried calling it in a way similar to python with no success:

fun(b="changed");
David Kamer
  • 2,677
  • 2
  • 19
  • 29

3 Answers3

2

This can be done by providing what the function sees in any situation where no parameters are defined:

((a="keep this", b="change this")=>{return a + b})(undefined, "changed");

Simply specifying the paramater position as undefined will cause the default value to be used. It's not as simply and direct as Python, however it will work in any situation where you know the number of arguments to skip.

Here is an example that can be used on more than one parameter and could be useful in a situation where many parameters need to be skipped:

((a="keep", b="this", c="change this")=>{
   return a+b+c
   })(...(new Array(2).fill(undefined)), "changed");
David Kamer
  • 2,677
  • 2
  • 19
  • 29
1

It is sufficient to create a new sparse array without filling.

const fn = (a = "keep", b = "this", c = "change this") => a + b + c;

console.log(fn(...new Array(2), "changed"));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

When you pass no argument to the a function, you are indeed passing undefined, so you can just do that for the first argument.

const f = (a="a", b="b") => console.log(">", a, b);
f(undefined, "new b") // > a new b

another way is to just use dict

const f = ({a="a", b="b"}) => ...
f({b: "b content"})
Rafael Quintela
  • 1,908
  • 2
  • 12
  • 14