.map() explained simply
Definition
.map(callbackFn)
in JavaScript is a higher order function (a function that either takes in another function as an argument or that returns another function). .map
is an Array method that allows you to loop over each element of array A and apply a callback function that you specify on each element. The return
results of each callback function will be stored in a brand new array B.
Get Started
We’ll start with the following array:
const arr = [1,2,3,4,5];
Let’s say we wanted to multiply every element in this array by 2? How would we do this? I suppose one way we could do this is by using a for-of
loop:
const newArr = [];
const arr = [1,2,3,4,5];
for(let num of arr)
newArr.push(num*2);
console.log(newArr); // [2,4,6,8,10]
But this is not necessary. We can simply use .map(callbackFn)
to loop over each element of arr
and apply a callback function to every element that will return (the current element * 2).
const arr = [1,2,3,4,5];
const newArr = arr.map((num) => {
return num * 2
});
console.log(newArr); // [2,4,6,8,10]
This is how we use .map
. We take the array we want to map over (arr
) and call arr.map(callbackFn)
. .map
takes in a callback function as an argument. .map
will start from the beginning of the original array and apply this callback function to every element. The num
parameter in the callback stands for the current element from the original array (arr
). Whatever the callback function returns will be the new value for that position.
So, because we are returning num * 2
in our callback, .map
goes over every element in arr
, multiplies each number by 2, and stores the new values in a new array.
NOTICE:.map
DOES NOT modify the original array. It creates a new array. That means that this code will not do anything useful:
const arr = [1,2,3,4,5];
arr.map((num) => {
return num * 2
});
console.log(arr) // [1,2,3,4,5] - Bad! .map does not modify the original array!
Also, we can take advantage of implicit return to make our .map
implementation cleaner and easier to read:
const arr = [1,2,3,4,5];
const newArr = arr.map(num => num * 2);
console.log(newArr) // [2, 4, 6, 8, 10]
Summary
.map(callbackFn)
is a higher order function for arrays that allows you to loop over each element of array A and apply a callback function that you specify on each element. The return
results of each callback function will be stored in a brand new array B.