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:
JavaScript
x
5
1
function x(a=1,b=2) {
2
console.log(a);
3
console.log(b);
4
}
5
and call x(3)
, it will use the 3 for a
and return “3, 2”
JavaScript
1
5
1
x(3);
2
3
=> 3
4
2
5
I want it so that the function instead uses the 3 for the b
parameter, and therefore returns “1, 3”
JavaScript
1
4
1
x(3);
2
=> 1
3
3
4
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
JavaScript
1
8
1
function x({a=1,b=2} = {}){
2
console.log("a",a);
3
console.log("b",b);
4
}
5
6
x();
7
x({a:10})
8
x({b:20})