MDN says:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
Seems complicated right? But it isn't. Let's see how.
๐ Hi Developers! This is the very first blog post of my life so let's just start!
If you know the forEach()
array method in JavaScript then it would be easy for you to understand the map()
method.
๐จ The map()
method is an array method which LOOPS OVER AN ARRAY and CREATES A NEW ONE as per the changes defined.
The process is as follows:
- It LOOPS over the array and has access to each item in the array in a callback function.
- We will CHANGE / MODIFY a specific or all of the items in the array
- And finally, we have to RETURN that item in the end
Let's understand this by an example
Say you have an array of words which are in present tense:
var presentWords = ["work", "play", "click", "end", "start"];
and you want to create a new array that will contain the same words but in past tense. We will add an ed
after each word for that. So we will define a new variable like this.
var pastWords = presentWords.map(function(word) {
return word + "ed";
});
Here, we have a callback function that has access to every item in the array and we concatenate ed
to each word and return it.
If we log pastWords
to the console, we will get this:
["worked", "played", "clicked", "ended", "started"]
Transforming to ES6
Now we did this in an old fashioned way of JavaScript. Let's make this look more clear with the ES6 arrow function, template strings, and constants
const presentWords = ["work", "play", "click", "end", "start"];
The arrow function can be like this:
const pastWords = presentWords.map(word => {
return `${word}ed`;
});
But we can get rid of the return
and the extra line and make it like this:
const pastWords = presentWords.map(word => `${word}ed`);
So we transformed the code from this:
var presentWords = ["work", "play", "click", "end", "start"];
var pastWords = presentWords.map(function(word) {
return word + "ed";
});
to this:
const presentWords = ["work", "play", "click", "end", "start"];
const pastWords = presentWords.map(word => `${word}ed`);
I also have a video on my channel about the array.map()
.
I hope you enjoyed and learned from this blog post. If you have any suggestions or feedback. Please let me know in the comments. Happy Coding