2

I know I can capture the rest of the parameters while destructing function parameters:

const f1 = ({ a, b, ...p }) => ...

f1({ a: 1, b: 2, c: 3, d: 4 })

then p contains c and d, but not a or b.

Is there a syntax that makes p contain all of a, b, c and d while at the same time, destructing a and b?

This is useful if inside f1 I need to call f2 with all the parameters.

Nan Li
  • 603
  • 1
  • 7
  • 18
  • 2
    Destructure the object inside the function: `const f1 = p => { const { a, b } = p; ... }` – adiga May 22 '19 at 19:56
  • that's not the sulotion. it kind of defeats the purpose of destructing function parameters, it will introduce statements in your function, make it less "functional" – Nan Li May 22 '19 at 20:02
  • 1
    Another alternative could be `const f1 = (p, {a, b} = p ) => ...` but this won't work if you expect to call your function with more than one parameter. – Shidersz May 22 '19 at 20:03
  • This is exactly the purpose of destructuring a parameter. You do it only when you care about some of the properties and not the full object. – adiga May 22 '19 at 20:12
  • @Shidersz, that works! and it's good enough for me, I tend to make all my functions take just 1 object parameter with everything inside. but I don't even recognize the syntax, looks like f1 expects 2 parameters. is there a name for this syntax? – Nan Li May 22 '19 at 20:12
  • And another one could be: `const f1 = ({ a, b, ...p }) => ((a, b, p) => {console.log(a, b, p)})(a, b, p = {a, b, ...p})` – Shidersz May 22 '19 at 20:12
  • This has been asked multiple times and it's the same solution. Some of them have alternatives like the one @Shidersz suggested [1](https://stackoverflow.com/questions/45145876), [2](https://stackoverflow.com/questions/40569983), [3](https://stackoverflow.com/questions/49075043), [4](https://stackoverflow.com/questions/54085341) – adiga May 22 '19 at 20:13
  • @adiga, there is a difference between destructuring an object in a statement and destructuring function parameters. the latter will allow you to avoid statements and the curly braces in the function, resulting in more functional code. and the latter is what I'm asking here – Nan Li May 22 '19 at 20:20
  • @Shidersz, got it, it's just a hack. basically moving the destruction statement from the function body to the function parameter – Nan Li May 22 '19 at 21:48

0 Answers0