-1

How do I send one or more variables in a JavaScript function without sending null values to unused arguments?

I have a function:

function setProjectParameters(trigger, pp_ts, pp_t, pp_bs, pp_dg, pp_ll){alert("the rest of the code is here doing something");}

Sometimes I want to call this function and only send a value to pp_bs, now I do it like this:

setProjectParameters(null,null,null,"8");

Can I do it something like this?: (It doesn't work so I guess not...)

setProjectParameters(pp_ts="44");

What is the proper way to do it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jayas
  • 1
  • 2
  • What _language_? In JavaScript, see e.g. https://stackoverflow.com/q/11796093/3001761. Note `undefined` is likely better than `null` for "no value", as that's the default for parameters _after_ the last supplied positional value. – jonrsharpe Jun 07 '22 at 13:33
  • thanks, I should have written that it's about Javascript – Jayas Jun 07 '22 at 14:50
  • As far as I know JavaScript doesn't support that. You can however "simulate" this if you change the function to accept an object and use [object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring) e.g. `function setProjectParameters({ trigger, pp_ts, pp_t, pp_bs, pp_dg, pp_ll })` and then call it as e.g. `setProjectParameters({ pp_ts: '44' })` – apokryfos Jun 07 '22 at 14:55

1 Answers1

-1

The easiest I think is to have the parameters in the function as an object and have defaults for them if you need to. Then you can target a specific parameter.

function setProjectParameters({trigger = 'if you need defaults add them like this', pp_ts, pp_t, pp_bs, pp_dg, pp_ll}){alert("the rest of the code is here doing something");}

Then use the function like this

setProjectParameters({pp_ts="44"});
Ivana Murray
  • 318
  • 1
  • 11