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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With