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.