tnkh
tnkh

Reputation: 1829

Default function parameters

Hi I have to admit that I am still grasping many ES6 syntax even though I have used a fair amount of them. For example, I understand that you can do console.log(multiply(5)) to get the result of a given function of

function multiply(a, b = 1) {
  return a * b;
}

But let say you have

function multiply(a, b = 1, c) {
  return a * b * c;
}

Obviously you can't do (console.log(multiply(5,,5)). In this case, is rearranging the arguments position in the function to become function multiply(a, c, b = 1) the only possible way? Or is there any other smarter way?

Upvotes: 4

Views: 513

Answers (4)

georg
georg

Reputation: 214949

Unfortunately, JS doesn't support elisions (skips) on function arguments, so you can't simply write

f(1,,2)

and expect the 2nd argument to be the default. You could use array elisions instead:

function f(a, b = 99, c) {
  console.log(a, b, c)
}


f(...[1,,2])

Not sure if this is worth the trouble though.

As @Dave Marshall mentioned, the most straightforward way it to pass undefined, I'd use it in a more readable form, that makes it clear which parameter is omitted:

function f(a, b = 99, c) {
  console.log(a, b, c)
}


f(1, void 'b', 2)

Upvotes: 1

Someone
Someone

Reputation: 3568

You can set your default parameter to be the first one, and then spread the rest. One benefit to this is that you're now not limited to just 3 numbers;

    function multiply(a = 1, ...args) {
        args = [a, ...args];

        return args.reduce((x, y) => x * y);
    }

    console.log(multiply(5));
    console.log(multiply(5, 10, 15, 20, 25));

Upvotes: 2

David Lehnsherr
David Lehnsherr

Reputation: 116

You can pass undefined to use default values:

function multiply(a, b = 1, c) {
  return a * b * c;
}

multiply(2, undefined, 3); // 6

You can read about default parameter values and see more examples at MDN

Upvotes: 6

CertainPerformance
CertainPerformance

Reputation: 370589

Another option is to pass a single object with default property assignment instead of multiple separate arguments:

function multiply({ a, b = 1, c }) {
  return a * b * c;
}

console.log(multiply({
  a: 3,
  b: 4,
  c: 5
}));
console.log(multiply({
  a: 3,
  c: 5
}));

Upvotes: 5

Related Questions