2

If I have a function with two different parameters, how can I make it so that if I input only one parameter, it will use the input as the second parameter rather than the first parameter? For example, if I have this function:

function x(a=1,b=2) {
    console.log(a);
    console.log(b);
}

and call x(3), it will use the 3 for a and return "3, 2"

x(3);

=> 3
   2

I want it so that the function instead uses the 3 for the b parameter, and therefore returns "1, 3"

x(3);
=> 1
   3
Lemondoge
  • 959
  • 4
  • 17
Nazeh Taha
  • 65
  • 1
  • 6
  • While this can technically be done, what is your use case? There is almost certainly a better alternative. – Andrew Nov 27 '20 at 20:44
  • 2
    `x(undefiined, 3)` but if you really want to have any parameter optional, you should probably pass an object. – VLAZ Nov 27 '20 at 20:44
  • Very related: [Set a default parameter value for a JavaScript function](https://stackoverflow.com/q/894860) – VLAZ Nov 27 '20 at 20:46
  • 1
    Does this answer your question? [How to pass the nth optional argument without passing prior arguments in JavaScript functions?](https://stackoverflow.com/questions/57040478/how-to-pass-the-nth-optional-argument-without-passing-prior-arguments-in-javascr) – Ivar Nov 27 '20 at 20:48
  • Thank you all, but is there any other way to achieve this than passing parameters as object – Nazeh Taha Nov 27 '20 at 20:56

2 Answers2

2

If you change your method to use a destructured object, you can pass an object with just the properties you wish to and default the rest

function x({a=1,b=2} = {}){
  console.log("a",a);
  console.log("b",b);
}

x();
x({a:10})
x({b:20})
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Use object destructuring approach

let a,b; 

/*
* define variable to avoid overwrite in large application
*/

function x({a=1,b=2} = {}){
  console.log( { a } );
  console.log( { b } );
}

x({b:20}) /* Passed only 'b' here */
GMKHussain
  • 3,342
  • 1
  • 21
  • 19