-1

I am trying to understand arrow functions in typescript at Arrow functions

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(element => element.length); // [8, 6, 7, 9]

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

I understood all except the last line. In the second last line, it accepts a single expression and returns element.length. Equivalent to {return element.length;}. But the last statement makes no sense to me.

Things that I don't understand:

  1. It is taking an object length.

  2. If it is single argument, why is it in ().

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
subtleseeker
  • 4,415
  • 5
  • 29
  • 41
  • 3
    Possible duplicate of [What do function parameter lists inside of curly braces do in es6?](https://stackoverflow.com/questions/37661166/what-do-function-parameter-lists-inside-of-curly-braces-do-in-es6) – JJJ Dec 23 '18 at 10:27

2 Answers2

1

If you look at that last line:

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

there are curly braces {, } around the length argument.

It's called Object destructuring assignment:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

JulianG
  • 4,265
  • 5
  • 23
  • 24
0

Map is destructuring the parameter which is passed to it. A string is passed to the map function in this case, and a string has many properties, one of which is length. So the string is destructured and its property, length, is set to the destructured length variable. +1 to JulianG...

Mustehssun Iqbal
  • 576
  • 3
  • 19