8

On MDN, the following code is used as an example of how arrow functions are used to write shorter functions.

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

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

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

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

I understand the two first. What exactly is going on in the last function?

Is it an ES6 object destructuring assignment (i.e. when a material String object is received as an argument from map, the length property of that string is destructured into a length variable, then returned by the arrow function)?

Magnus
  • 4,901
  • 5
  • 31
  • 62
  • 3
    Destructuring, yes. Destruction, definitely no. – Bergi Jan 21 '18 at 21:39
  • It's not an assignment but a parameter declaration, but yes it's the same destructuring syntax and it works the same as in an assignment expression. – Bergi Jan 21 '18 at 21:42
  • String objects have a length property. So, that object property is getting unpacked: => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter – Patrick H Jan 21 '18 at 21:43

3 Answers3

5

Yes, this is destructuring.

material is an object and you can get his properties in a neater and readable way.

instead of doing this:

materials.map((material) => {
  return material.length;
});

you use ES6 to extract { length } property out of the material object, and you're getting this:

materials.map(({length}) => length); 

Also, in an arrow function you don't have to wrap the function with {}, if its a one-liner, and if you don't wrap it with {} you can also omit the return keyword, the function will return it automatically.

You can read more about it here:

https://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/

Kos
  • 3,847
  • 8
  • 29
  • 34
Nir Ben-Yair
  • 1,392
  • 11
  • 16
5

You could look at the first element of the iteration with 'Hydrogen' as element for destructuring assignment.

'Hydrogen' has a length property, because it is a string, which has a length property. This value is taken and assigned to length variable and later used in the callback as return value for a new array.

var { length } = 'Hydrogen';

console.log(length);
Sébastien
  • 10,675
  • 11
  • 47
  • 67
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
-3

{length} is the .length of the elements of the array, e.g., "Hydrogen" .length is 8

guest271314
  • 1
  • 10
  • 82
  • 156