Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Arrow Function with Destruction? [duplicate]

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)?

like image 992
Magnus Avatar asked Jan 21 '18 21:01

Magnus


2 Answers

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);
like image 94
Nina Scholz Avatar answered Oct 05 '22 03:10

Nina Scholz


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/

like image 45
Nir Ben-Yair Avatar answered Oct 05 '22 03:10

Nir Ben-Yair