0

If I have a function declared with two default parameters, like this:

const doSomething = (defaultVal = 'me default', useThis = false) => {
      /* ... */
};

And I want to call the function passing in an argument for the second parameter, but have the first argument just use the default value:

doSomething(???, true);

Is there some syntax for telling the function to use the default parameter, or does a real value need to be passed in?

  • 1
    Pass `undefined`. – Bergi Jun 13 '22 at 13:06
  • I'd advise against using default values if it's not just the last parameter. If you have two (or more) parameters and you want a non-last to have a default, it gets awkward to write `foo(1, "two", undefined, "hello", 42)`. Instead use an object as input. It mimics passing in named parameters, so you can pass any you want. The function can then default the rest. – VLAZ Jun 13 '22 at 13:09

2 Answers2

4

Pass in undefined

const doSomething = (defaultVal = 'me default', useThis = false) => {
  console.log({ defaultVal, useThis });
};

doSomething(undefined, true)
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

There is no syntax or key for that purpose. You should use default parameters as last. For that example if useThis parameter will be given a value for everytime you can give useThis as first argument.

Alternatively you can give an object as parameter. Inside the function you can merge your template (default valued object) and argument object then use it in you function.

const fn = (props) => {

    const newProps = {
        defaultVal : "default",
        useThis : false,
        ...props
    }

}