Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge passed function parameter with default parameter [duplicate]

What's the most efficient way to merge a default function parameter as of the latest versions of JavaScript?

What I would like to achieve:

var defaultParam = {a: 1};

function foo(param = defaultParam) {
   // desired result : param = {a: 1, b: 2}
}

var passedParam = {b: 2};
foo(passedParam);
like image 251
ougkr Avatar asked Dec 04 '25 15:12

ougkr


1 Answers

You can use that inside the function and not as a default param for the function. Because the way you expect, whenever you send a value to the function it will overwrite the default value so the better approach is to get that object prepared for the function param inside the function.

var defaultParam = {a: 1};

function foo(param) {
   let newParam = {
     ...defaultParam,
     ...param
   }
   console.log(newParam);
}

var passedParam = {b: 2};
foo(passedParam)

In that case, you can even take var defaultParam inside the function or use it directly as:

function foo(param) {
   let newParam= {
     a: 1,
     ...param
   }
   console.log(newParam);
}
like image 100
Ankit Agarwal Avatar answered Dec 07 '25 05:12

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!