0
I don't understand ES6 objects and destruction please help me
3 Antworten
+ 8
its simpler way to extract a variable from object properties,
for example object obj has x and y.
obj = {x:22, y:33}
normally you need to do it like this
let x = obj.x;
let y = obj.y;
same result with destructuring
let {x, y} = obj
you dont even have to use them all
let {x} = obj
or if you need a different name
let {x:newX} = obj
//but using x will thrown an error.
//since its renamed to newX
//so newX is safe to use
what if the variable you need is not in the object ? you can add a default valur as a failsafe
let {y,z=55} = obj
//now z=55 because z isnt in obj
when its useful ? ever had a case like this ?
let x = obj.foo.bar.foobar.x
let y = obj.foo.bar.foobar.y
yes, its so annoying to retype everything everytime, and there's a possible typo everywhere. witn this es6 thing, its much less annoying, and only 1 possible typo of long sequence of object properties.
let { x, y } = obj.foo.bar.foobar
+ 7
Bibek
Read the comments in the lessons as you can find great examples and explanations.👍
• https://code.sololearn.com/W30AcwbyzkXq/?ref=app
+ 1
https://www.sololearn.com/learn/JavaScript/1151/