0

I was reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions which contains the following code snippet:

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

elements.map(function(element ) { 
  return element.length; 
}); // [8, 6, 7, 9]

elements.map(element => {
  return element.length;
}); // [8, 6, 7, 9]

elements.map(({ length }) => length); // [8, 6, 7, 9]

The last application of the arrow function seems very concise, as it does not even use the dummy variable element. However, it is not clear to me how this works; I've seen how ({}) can be used on the right-hand side of an arrow function to return an object literal, but I haven't seen any examples of using it on the left-hand side.

Can someone explain the syntax of the last arrow function?

Kurt Peek
  • 34,968
  • 53
  • 191
  • 361
  • 1
    Relevant dupes: https://stackoverflow.com/q/34414766/1848654, https://stackoverflow.com/q/26999820/1848654 – melpomene May 28 '18 at 17:37
  • 1
    The part of that answer you're looking for is Destructuring of function parameters. – Paul May 28 '18 at 17:38
  • 1
    since `length` is just a property of the String object, you can pattern match on it... – mb21 May 28 '18 at 17:40
  • I found http://exploringjs.com/es6/ch_destructuring.html a useful reference; in this context, the `{ length }` is short for `{ length: length }`. The second `length` is essentially the dummy variable for this arrow function; for example, it also works as `elements.map(({length: l}) => l);` – Kurt Peek May 28 '18 at 18:07

0 Answers0