+ 10

Destructuring in javascript?

This topic is playing with my mind a lot var obj = {id: 42, name: "Jack"}; Let {id = 10, age = 20} = obj; console.log(id); // 42 console.log(age); // 20 My doubt : why the id is assigned 10 .I mean why? var o = {h: 42, s: true}; var {h: foo, s: bar} = o; //console.log(h); // Error console.log(foo); // 42 mydoubt: In this code ' : ' is used in the second line of code When is ' = ' is used and when is ' : ' is used? David Carroll Luis Febro 🇧🇷 Igor Makarsky Airree

7th Jul 2019, 9:34 AM
John Dhinakar
John Dhinakar - avatar
9 Respuestas
+ 14
':' colon is for renaming the destructure variable name, if you rename the variable h:foo you cant call previous name becuz its already rename and unavailable. '=' equal is for assigning default value if the value of id: '' and Jack: '' is undefined the id =10 will be result and in case of age it is not in obj so its undefined age =20, default value 20 is the result Hope this might clear.
7th Jul 2019, 2:00 PM
Danielov
Danielov - avatar
+ 9
I suggest you to read the documentation down to the smallest detail here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment There are many examples of usage for both array and object destructuring for you to scrutinize them. This is how you will learn the topic better. It is true what Airree related in his second paragraph. This can be annoying, pal. Send a DM for a specific person friendly and moderately and avoid tagging people here in Q&A Discussions. I know that you wanna learn a lot, but try using your energy by reading real DOCUMENTATION about JS like MDN web docs. You can be as learning hungry as you want to over there. 👍
7th Jul 2019, 11:03 AM
Luis Febro 🇧🇷
Luis Febro 🇧🇷 - avatar
+ 8
= means you give it an optional value. If the object property cannot be found, it will be assigned that value. : means you "rename" it. The object's "h" property will be named as foo. Please stop tagging random people at the end, you will probably get an answer very quickly without it
7th Jul 2019, 9:48 AM
Airree
Airree - avatar
7th Jul 2019, 11:09 AM
John Dhinakar
John Dhinakar - avatar
+ 2
Tq daneillonge you explained it very well😊🙏
7th Jul 2019, 2:10 PM
John Dhinakar
John Dhinakar - avatar
+ 2
watch object destructure in youtube hope it will make you clear.
9th Jul 2019, 3:25 AM
Danielov
Danielov - avatar
+ 1
Danielov is absolutely right.
8th Sep 2019, 7:24 AM
Abdul Aleem Baig
Abdul Aleem Baig - avatar
0
I don't understand it
7th Jul 2019, 9:37 PM
Samuel Oga
0
Cara membuat.mi?
18th Jul 2019, 2:12 PM
Darman