0

I am having difficulty understanding arrow function in javascript. I looked up in MDN and found this code.

var res, elements = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

//First
res = elements.map(function(element) {
  return element.length;
});
console.log(res);

//Second
res = elements.map(element => {
  return element.length;
});
console.log(res);

//Third
res = elements.map(({length}) => length);
console.log(res);

I get the first and second way just fine, but the third method makes no sense to me.

First: I didn't understand what these 2 brackets () and {} in ({ length }) are.

Second: The first word lenght also makes no sense. Is it just some random variable?

Anybody willing to shed some light would be very helpful. Thanks in advance!

eisbehr
  • 12,243
  • 7
  • 38
  • 63
subtleseeker
  • 4,415
  • 5
  • 29
  • 41
  • 3
    That's [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), in this case in the parameter list but it works exactly like it does in assignment. You need the outer `()` because when the parameter list of an arrow function is anything other than one simple parameter (like `element`), you have to have `()` around the arrow function's parameter list. Then, within those `()`, the `{length}` indicates destructuring (taking the `length` property from what's passed in). – T.J. Crowder Jun 14 '18 at 07:29
  • 1
    The longer form still using destructuring (but assignment this time instead of in the parameter list) would be: `.map(element => { let {length} = element; return length; })` – T.J. Crowder Jun 14 '18 at 07:31

0 Answers0