Array.prototype.map()
When you start learning JavasScript (JS) pretty soon you will run into an array. An array is a data type in JS which allow you to store information/values as a list. To create an array you can simply write your list of values inside of a pair of square brackets, with a comma separating the values.
Example:
let teamSeven = ["Naruto", "Sasuke", "Sakura", "Kakashi"];
Once you have an array, it is very likely that you will want to do something with it later. At the beginning of your JS journey, you will come across for
loops which you can use to iterate through something and it gives you the power to run a block of code a certain number of times. If you know that you want to loop through your array, one of the methods you can use is .map()
.
How to use .map()
One important concept to remember when working with .map()
is that it creates a new array and leave the original array unchanged. This is important because not all methods behave this way and can cause bugs in your program.
Imagine you want to change all the values in your array (above) by adding some extra information about each of the teamSeven members. All you have to do is call .map()
on the array and pass in a callback function* as an argument. Observe.
*When you pass a function as an argument of another function, that function is called a callback.
Example:
function addVillage(str) {
return str + " of Konoha";
}
let revampedTeamSeven = teamSeven.map(addVillage);
console.log(teamSeven, revampedTeamSeven);
/* ["Naruto","Sasuke","Sakura","Kakashi"] ,
["Naruto of Konoha","Sasuke of Konoha","Sakura of Konoha","Kakashi of Konoha"] */
In the above example, .map()
passes each value as a an argument to our addVillage(str)
function, which runs and the returned value is stored into the new array.
Summary
Array.prototype.map():
- Creates a new array by calling the provided callback function on each of the value in your array.
- It does not change the original array.
- It runs the callback function once on each value of the array.
- The newly created array will have the same length as the original array.
For more detailed information about this method checkout the official documentation on MDN - Mozilla.
I hope that was easy to read, any feedback please let me know, I am trying to strengthen my knowledge through teaching.
Top comments (1)
Well written!