0

Say I have this function:

const myFn = obj => doSomethingWithKey(obj.key);

I can use destructuring, which is much more elegant:

const myFnV2 = ({key}) => doSomethingWithKey(key);

But can I assign within the function definition both key and obj variables?

Like this:

const otherFn = obj => {
  const {key} = obj;
  doSomethingWithObjAndKey(obj, key);
}

But in one line. I hoped this would work:

const otherFn = ({key} = obj) => doSomethingWithObjAndKey(obj, key);

But it doesn't as it sets obj as the default value to the {key} param. :(

I know that this would work:

const otherFn = obj => doSomethingWithObjAndKey(obj, obj.key);

But this reads quite differently, and the obj.key variable can't be used in an object directly whereas {key} can.

My guess is that it doesn't exists at the moment, since my research on the topic failed, but my question is: is there such proposal for a future ES version?

It is possible in Elixir for instance, and it is highly useful: ex. def my_fn(%{id: id} = params)

And it doesn't feel like much complicated to babelize, besides finding a proper syntax since = is already used, which may induce backward compatibility issues.

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206
  • 1
    You can do the following: `const myFnV2 = (obj, {key}=obj) => doSomethingWithObjAndKey(obj, key);`. This basically creates a function with two parameters and initializes the second one with the value of the first one. I'm not saying that this is a good approach but it's possible. – Felix Kling Apr 07 '22 at 07:59
  • Ugly but interesting hack! Thanks – Augustin Riedinger Apr 07 '22 at 12:33

0 Answers0