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

Asked

Viewed 601 times

0

I was studying and this code appeared:

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

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

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

2 answers

3

Then, the map function will scroll through the array and send as parameter to the callback you provide each element of this array. Its return is a new array with the callback return you defined.

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

3


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

The function map that 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;
  })
);

Thus it is perhaps clearer than the map will pick up on 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. Each being material one string the .length will give the amount of characters each has.

Note that I am abusing a little Portuguese to make it easy to understand, because the map does not change the original array. Only returns a new one with the mapping of each element.

It could however map to anything else it intended, such as mapping each material to everything in uppercase:

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

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

Even using Arrow Functions could have the return:

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

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

But how the return is implied when there is no {} ends up being written this way that is simpler and straightforward.

As last note be careful when you write length that in your case has a spelling error (wrote lenght) which is very common to happen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.