30

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

Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173
Kermit
  • 2,865
  • 3
  • 30
  • 53
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Andy Feb 08 '18 at 09:57

1 Answers1

45

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;
});
Ori Drori
  • 183,571
  • 29
  • 224
  • 209