I understand that, using ES6 syntax, a function can be made that takes an object as a parameter and that parameter can have a default value, like so:
function exampleFunction(objParam = {val1: 1, val2: 2}) {
//...
}
If I call exampleFunction()
,objParam
is given the default value. However, if I call exampleFunction({val1: 3})
, objParam.val2
is undefined
. This makes sense, because the default isn't being applied. Is there any way I can make sure that objParam.val2
does have a value, using the ES6 notation? I know I can add checks within the function, but that introduces inconsistency in the code and I'd rather not.
Edit: To clarify, here is a better example:
function exampleFunction(param = 0, objParam = {val1: 1, val2: 2}) {
return objParam.val1;
}
exampleFunction(); // Returns 1 (this is good)
exampleFunction(1, {val1: 2}); // Returns 2 (this is good)
exampleFunction(1, {val2: 3}); // Returns undefined (I want it to return 1)
And here's what I currently have, which does work but is somewhat inelegant:
function exampleFunction(param = 0, objParam = {val1: 1, val2: 2}) {
if(objParam.val1 === undefined) objParam.val1 = 1
if(objParam.val2 === undefined) objParam.val2 = 2
...
}
Object.assign
– Blinny