What is the difference between map () and lenght ()?

0

I was studying and this code appeared:

var materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

console.log(materials.map(material => material.length));

From what I understand, it scans the array and returns another array with the number of letters of each word, but how does this happen? If the map function returns the "words" of the array and the lenght also?

    
asked by anonymous 20.01.2018 / 17:21

2 answers

3

The map gets a function that is applied to each element, and the return of that function constructs all the new elements mapped .

The function map you indicated could have been written like this (without Arrow Functions ):

var materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];

console.log(
  materials.map(function (material){
    return material.length;
  })
);

So it is perhaps clearer that map will get in each material and in place of that material put another element that will be the return of the past function, in this case the .length of material . Being each material one string the .length will give the amount of characters that each one has.

Note that I'm taking a little bit of Portuguese to be easy to understand because map does not change the original array. It only returns a new one with the mapping of each element.

You could however map to anything else you wanted, such as mapping each material to all caps:

var materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];

console.log(
  materials.map(function (material){
    return material.toUpperCase();
  })
);

Even using Arrow Functions could have return :

var materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];

console.log(
  materials.map(material => {
    return material.length;
  })
);

But since return is implicit when it does not have {} it is written in this way that is simpler and more straightforward.

As a last note be careful when writing length which in your case has a misspelling (wrote lenght ) which is very common to happen.

    
20.01.2018 / 21:19
3

Then the map function will cycle through the array and will send as a parameter to the callback that you supply each element of this array. The return of it is a new array with the callback return you have set.

The length property only gives you the size of the array.

console.log([1, 2, 3]) // retorna 3, que é  tamanho do array
console.log([1, 2, 3].map(val => val * 2) // retorna um novo array com osvalores 2, 4 e 6
    
20.01.2018 / 17:28