I am pretty new to javascript. saw this on MDN regarding arrow functions.
Can anyone explain to me how does the 2nd one work? I understand the first one. Not quite sure why we put length in an object, and then return the length???
Case 1 (which i understand from how it transformed from ES5):
materials.map((material) => {
return material.length;
}); // [8, 6, 7, 9]
Case 2 (not getting what {length}
is doing here and also why do we return length
:
materials.map(({length}) => length); // [8, 6, 7, 9]
Thank you so much!
Update:
So reading from the answer from Jeff B. It appears that the 2nd one is doing the following with destructuring:
materials.map(({length}) => length)
in which {length}
will set a variable var length
to equal to materials.length
; and that's why we can simply return length
. That makes sense. Thanks Jeff
This uses a destructuring assignment to get at the length
property without saving the whole object. Specifically, this is a case of "object destructuring".
For instance:
let yourObject = {foo: 1, bar: 2}
let {bar} = yourObject;
// bar now equals 2
With this in mind, you can see how ({length}) => length
sets the name length
to the length
property of the first parameter and then immediately returns it—making the two expressions equivalent.