Home > Net >  An argument with default value precedes non-default argument in JavaScript
An argument with default value precedes non-default argument in JavaScript

Time:03-29

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 setting the value for b?

CodePudding user response:

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 }));

CodePudding user response:

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
  • Related