Can someone explain me the reason why :
const param = {hello: "Hello", world: "world", name: "Patrick"}
const variable = {hello, world} = param;
Will set my variable to :
{hello: "Hello", world: "world", name: "Patrick"}
And not
{hello: "Hello", world: "world"}
Or even undefined why taking this choice ?
I’m curious !
Advertisement
Answer
The value of an assignment expression is the right-hand side of the assignment. So {hello, world} = param performs a destructuring assignment to hello and world, but its value is the entire param object. This is then used as the value in the initialization of variable. So it’s effectively equivalent to:
const variable = (hello = param.hello, world = param.world, param);
Note also that you’re not declaring the hello and world variables, these are just being assigned. They’ll be global variables if they’re not previously declared in the scope.