+ 1
Explain this code
let arr =[] for(let {x=3, y=2} of [{x:1}, {y:4}]){ arr.push(x,y) } console.log(arr) //1234
1 Answer
+ 2
Danielov,
https://code.sololearn.com/Wkk8MBn7Ldwm/#js [might be a better explaination]
Iterating over an array of objects but with an ES6 twist, object destructuring.
Object destructuring is an expression that unpacks properties from an object, into distinct variables. In this case variables, x and y coincide the property names within each object of the array. You can also give the variables default values such as x=3, y=2.
So each object in the array is unpacked and if the object has a property named x or y its value is then assigned to the matching variable of the expression. If anyone of the properties is not a part of the object then the default values are used. And of course, x and y are then pushed to the array arr.
Ref Destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment