I am trying to understand some shorthand ways of writing ES6. What I cannot fully understand in the example below is the last shorthand "({length})" - I comprehend that it does work, and that it gets the length property of the array, but not why. How could this syntax be applied in another scenario, not involving arrays?
//Declare array
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
//Long version - ok
materials.map(function(material) {
return material.length;
});
//Arrow function - ok
materials.map((material) => {
return material.length;
});
//Shorthand arrow function - ok
materials.map(str => str.length);
//What? :)
materials.map(({length}) => length));
The example above is from the mozilla documentation of arrow functions. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
The length
is a property of strings, and can be destructured and returned in the map.
It's mostly the same as:
materials.map((str) => {
const {length} = str;
return length;
});