-1

I have a question for using optional arguments in function. Here is an example:

function add (num1=2,num2=3){
   return num1+num2
}
console.log(add(4,2)) // 6
console.log(add(5)) // 8
console.log(add()) //5

This work correct, but what if I want to pass only num2 as argument without num1 like this:

console.log(add(6)) 

Here this argument will be num2 not num1 which will return 8

  1. i don't want to use object as argument
  2. i don't want to pass undefined as first argument like this:

    console.log(add(undefined,5))

i want to achieve like express.js :

enter image description here enter image description here

How can I do this. Any help.

adel
  • 3,436
  • 1
  • 7
  • 20
  • 1
    Does this answer your question? [Is there a way to provide named parameters in a function call in JavaScript?](https://stackoverflow.com/questions/11796093/is-there-a-way-to-provide-named-parameters-in-a-function-call-in-javascript) – dwb May 14 '20 at 19:11
  • You can take advantage of destructuring but then you have to modify your function to accept object. – Hassan Imam May 14 '20 at 19:12

4 Answers4

1

try passing it in an object

function add ({ num1 = 2, num2 = 3 }) {
  return num1 + num2;
}

Manish Sundriyal
  • 611
  • 6
  • 16
0

just pass undefined in instead of a value

add(undefined, 6)

reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

you may be also interested in rest parameters:

/** 
 * @returns sum of passed args
 */
function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

if this doesn't satisfy you there's no other way without changing the function signature

roomcayz
  • 2,334
  • 4
  • 17
  • 26
0

Use:

add(add.num1,6); 
//returns 8

or

add(this.num1,6);

EDIT:

The JS parser does not require that the number of arguments match the function declaration. However, you must somehow inform JS which arguments you mean. By default, they are used in the order in which you declared them in the function. Using primitives as in your example you have to give something as argument 1. If you do not want to pass a specific value, you should explicitly indicate that you are using the default value, e.g. using this.num1, using undefined will also give the correct result but it is not clear what the programmer's intentions are.

Slawomir Dziuba
  • 1,265
  • 1
  • 6
  • 13
0

Try this one :

function add (num1 = this.num1 || 2, num2 = this.num2 || 3){
   return num1+num2;
}

console.log(add.call({num1:3}));
console.log(add.call({num2:6}));
TRK
  • 188
  • 1
  • 7