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
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
An arrow function can not be used as constructors. An arrow function can not use yield within its body. Arrow function cannot be suitable for call apply and bind methods.
map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
map always returns an array. It doesn't matter how you use that return value.
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; });
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