1

Following on Is there a way to provide named parameters in a function call in JavaScript?
I'm doing something like this:

function myFunction({param1, param2}={}){
  // ...function body...
}

myFunction({ param1 : 70, param2 : 175});  

So i was wondering is there a way to do this:

function myFunction(params = {param1, param2}={}){
  doSomething(...params)
} 

I think its clear i want to be able to spread the parameter object inside another function instead of specifying each parameter, but doing it like

params = {param1, param2}={}  

will result in errors saying param1 and param2 are not defined!, so i know this is not the way, so any idea how this can be achieved or maybe its not possible in the first place?

Ali Ahmadi
  • 701
  • 6
  • 27
  • 2
    Did you tried using `doSomething(...Object.values(params))`? It will spread all the values in the object. – smtaha512 Dec 25 '19 at 13:05

1 Answers1

3

Is this what you're looking for?

function myFunction (params) {
    const {
        param1 = /* default value */,
        param2 = /* default value */
    } = params;

    doSomething(params);
} 

Update #1

As you stated, in order to get IDE assistence, you might want to not use the answer above. As an alternative you can use the arguments object and pass it to doSomething using apply method. Also note that arguments is not available in arrow functions.

function myFunction ({param1, param2} = {}) {
    // forward all arguments including "this" to "doSomething"
    doSomething.apply(this, arguments);
} 
frogatto
  • 28,539
  • 11
  • 83
  • 129
  • 1
    If you take a look at https://stackoverflow.com/questions/11796093/is-there-a-way-to-provide-named-parameters-in-a-function-call-in-javascript you can see the whole point of named parameters is so that the IDE can show you the parameters you can enter inside the function, which is why your answer is not what i'm looking for. – Ali Ahmadi Dec 25 '19 at 13:09
  • 1
    @AliAhmadi To get IDE assistance, I suggest using TypeScript. – frogatto Dec 25 '19 at 13:13
  • 1
    I understand the alternatives, but the goal my question is simply to see if there is a way to accomplish what i explained, and if there isn't a way, i'd like to know. – Ali Ahmadi Dec 25 '19 at 13:16
  • 1
    I didn't know about arguments!, just what i was looking for, i'm going to leave the question open for a couple days and if there are no better answer i will accept yours, thanks! – Ali Ahmadi Dec 25 '19 at 13:24