Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preventing the defaults of unset object properties from being overridden in a JS function

So, I have a function with an object as a parameter:

function example(options = { param1: true, param2: 42 })
{
   return options.param2;
}

The problem is, if I call the function with parameters like this:

example({ param1: false });

the default for options.param2 gets overridden and set to undefined, even though it wasn’t defined when the function was called. I realize why this is (the object is all one parameter so the entire thing gets set when you call the function), but is there any easy way to prevent this from happening, short of making all of the object parameters their own arguments in the function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Destructure the argument instead, and assign default destructured values.

function example({ param1 = true, param2 = 42 } = {}) {
   return param2;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading