4

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?

5
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Like you can see here, try to run it.
    – Roy Berris
    Commented Apr 1, 2019 at 10:03
  • 1
    default parameters must be the last ones to be defined. or you call it like multiply(1, undefined, 2)
    – arizafar
    Commented Apr 1, 2019 at 10:09
  • @AZ_ default parameters can be anywhere in the argument list. Did you confuse it with the spread operator? Commented Apr 1, 2019 at 10:10
  • @SebastiaanYN I meant its a good practice to do so, that's why I have added how you will have to call the function with params with default values defined in between.
    – arizafar
    Commented Apr 1, 2019 at 10:12
  • Thanks a lot guys for your wonderful answer :)
    – tnkh
    Commented Apr 1, 2019 at 12:17

4 Answers 4

6

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

5

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

2

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

1

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.