Let's say I have the following function:
function fun(a,b) {
if(a) { //condition can be different
console.log(a);
// some other code
}
if(b) { //condition can be different
console.log(b);
// some other code, not necessary same as above
}
}
Now I know that I can call the above function like this:
fun(1,2) // a=1, b=2
fun() // a=b=undefined
fun(1) // a=1, b=undefined
But I want to do something like this:
fun(2) // a=undefined, b=2
I want to pass only one param which is assigned to b and not a.
In c# it can be done like this:
fun(b: 2) // assign b=2
So is there any way to do this in JavaScript?
An approach that I have in mind is
Instead of passing two arguments pass one object that contains the arguments.
Something like this:
function fun(obj) {
if(obj.a) {
console.log(obj.a);
// some other code
}
if(obj.b) {
console.log(obj.b);
// some other code, not necessary same as above
}
}
Using the above I can pass specific params only.
But is there any approach which will not contain any modification in the function.
Note:- I don't want to pass null or undefined as the first argument and then pass the second argument.