javascripttypescriptfunctionvariablesmultiple-arguments

Access 2 arguments in a function out of order?


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.


Solution

  • 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.