Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 434
tnkh Avatar asked Dec 08 '22 12:12

tnkh


1 Answers

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

like image 134
David Lehnsherr Avatar answered Dec 11 '22 08:12

David Lehnsherr