0

Is it possible to use a destructoring assigment when invoking a function?

Something like this:

function myFunc(one, two) { ... }

const functionArgs = {
    one: 1,
    two: 2
}

myFunc(...functionArgs);
Nick Muller
  • 2,003
  • 1
  • 16
  • 43
  • 1
    Javascript functions don't have *named arguments*. Arguments are only passed by position, and objects aren't necessarily keeping positions. So… no, not like this. – deceze Aug 27 '19 at 12:48
  • What if functionArgs was an array instead? Would that be possible? – Nick Muller Aug 27 '19 at 12:49
  • 2
    In that case, you'd be spreading the arguments - it's not a destructuring assignment. – VLAZ Aug 27 '19 at 12:50
  • 1
    You might want to use an object as params, this works really well with destructuring. – Keith Aug 27 '19 at 12:50
  • 2
    Be more logical to do `const myFunc = ({one, two}) => { console.log(one, two) }; const functionArgs = { one: 1, two: 2 }; myFunc(functionArgs);` – epascarello Aug 27 '19 at 12:51
  • Sadly the func is not one if my own APIs, or else I would use those solutions. – Nick Muller Aug 27 '19 at 12:52
  • so than you would need to use an array and not an object – epascarello Aug 27 '19 at 13:02
  • *"Sadly the func is not one if my own APIs,"* if these arguments are such a nuisance to you, don't spread that throughout your code. Use a more convenient adapter: `function notMyFunc(one, two) { ... }` `const myFunc = ({ one, two }) => notMyFunc(one, two);` and then use it `myFunc({ one: 1, two: 2 });` – Thomas Aug 27 '19 at 14:32

1 Answers1

1

Destructuring objects won't work but you can spread arrays.

function myFunc(one, two) { 
  console.log(one, two)
 }

const functionArgsObj = {
    one: 1,
    two: 2
}

const functionArgsArr = [
    1,
    2
]


// myFunc(...functionArgsObj); throws error

myFunc(...functionArgsArr); // works as expected (output: 1, 2)
user1984
  • 5,990
  • 2
  • 13
  • 32
  • As someone already commented, that's technically a spreader. But I'll take it! Thanks! :) – Nick Muller Aug 27 '19 at 12:54
  • Ahh great! I always get confused with the naming of spread and destructuring operator. I think this time I won't forget about it :D – user1984 Aug 27 '19 at 12:57