Skip to content
Advertisement

Pass the last parameter to function – JavaScript

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

Advertisement

Answer

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})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement