Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 arrow functions and array.map [duplicate]

Tags:

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

like image 226
Kermit Avatar asked Feb 08 '18 09:02

Kermit


People also ask

What does => mean in ES6?

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.

What is a reason to not use an ES6 arrow 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.

Does map method change the original array?

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.

Does map return a copy?

map always returns an array. It doesn't matter how you use that return value.


1 Answers

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; }); 
like image 165
Ori Drori Avatar answered Oct 05 '22 04:10

Ori Drori