Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that takes an object with optional/default properties as a parameter?

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
    ...
}
like image 605
Ian Avatar asked May 08 '18 15:05

Ian


People also ask

What is an optional parameter in a function?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.

What are default and optional parameters?

By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition.

What is default function parameter?

Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.


1 Answers

Probably not as clean as you're looking for, but you can do this instead

function exampleFunction(objParams) {
  const defParams = { val1: 1, val2: 2 };

  const finalParams = { ...defParams, ...objParams }
  // final params takes the default params and overwrites any common properties with incoming params

  // ...
}
like image 156
Sam Avatar answered Nov 10 '22 09:11

Sam