Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't we destruct objet and in order to create new variable : JS

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{hello: "Hello", world: "world"}

Or even undefined why taking this choice ?

I’m curious !

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading