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)?
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);
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With