0

In JavaScript it's possible to define a function like this:

function func(a = 10, b)
{
  return a + b;
}

How does one call this function by only specifying the value for b?

  • `func(undefined,1)`? – nicael Mar 28 '22 at 20:57
  • 2
    possible duplicate of [Set a default parameter value for a JavaScript function](https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function), also see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/default_parameters – nicael Mar 28 '22 at 21:00

2 Answers2

3

It'd only be possible by explicitly passing undefined, and by also providing a default for the second argument.

function func(a = 10, b) {
  return a + b;
}

console.log(func(undefined, 5));

But this is quite weird - it's very confusing. I'd highly recommend not doing this at all - either put the arguments with default values at the end, or in an object.

function func({ a = 10, b }) {
  return a + b;
}

console.log(func({ b: 5 }));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks, I actually came across this syntax in Redux using TypeScript as providing a default argument for the reducer state was the only way to make `createStore` work. It felt strange, so I was wondering why that would be the case. –  Mar 28 '22 at 21:10
0

If you are okay with currying the first parameter:

bind saves the function with the arguments supplied, so when one calls it, it calls it with the arguments applied. The first argument is what to bind this to, so the second argument will bind to a:

function func(a, b) { 
    return a + b;
}

newFunc = func.bind(null, 10)
newFunc(2)
12
run_the_race
  • 1,344
  • 2
  • 36
  • 62