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.