2

Say I have a function that has (A, B, C, D, E) arguments. Foo(A, B, C, D, E) But I don't need them all the time. Sometimes I just need A and C for example. Right now I would have to call it like this: Foo('beef', '', 'sour cream', '', '')

But those blanks irritate me. Is there a way to say to make it just be Foo('beef', 'sour cream')? Maybe Foo(A='beef', C='sour cream')?

I've tried making them optional, but as I understand it, I can't expect the program to understand I want B blank. It expects 5 arguments, it needs 5.

Kjata1013
  • 35
  • 6
  • 4
    https://travishorn.com/using-the-options-object-js-pattern-221f083aadbc – Trevor Dixon Feb 10 '23 at 17:47
  • 2
    https://stackoverflow.com/questions/12826977/multiple-arguments-vs-options-object – Trevor Dixon Feb 10 '23 at 17:48
  • 2
    Use an options object instead of arguments (as stated above) – EpicPuppy613 Feb 10 '23 at 17:49
  • 1
    *"`Maybe Foo(A='beef', C='sour cream')`"* - You're close actually, but the syntax is slightly off. You can use multiple arguments, with default values, placing optional ones at the end of the list (unless they're _all_ optional), or a single object with keys, `{a: 'Beef', c: 'Sour Cream'}`, etc. – Tim Lewis Feb 10 '23 at 17:50
  • Thank you all, I appreciate the time. I hope I didn't waste yours. Thank you so much! – Kjata1013 Feb 10 '23 at 18:02

1 Answers1

3

You can name them like this:

function foo({A, B, C, D, E}) {
}

foo({A:3, D:5})

What we're technically doing here is passing an object, and using destructuring to extract the properties of the object into local variables.

Andrew Parks
  • 6,358
  • 2
  • 12
  • 27