3

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

geekydude703
  • 187
  • 1
  • 1
  • 13
  • Glad to help! If my answer is enough to consider your problem solved, please [accept the answer](https://stackoverflow.com/help/someone-answers) by clicking the checkbox to the left of it. That way future users can find it, and other potential answerers know you've got a solution. Good luck in your ES6 exploration! – Jeff Bowman Feb 15 '18 at 23:49
  • Thanks Jeff. You are a great guy. – geekydude703 Feb 15 '18 at 23:51

1 Answers1

3

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.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251