JavaScript provides us with the very helpful map method to work with arrays. It can be used in scenarios where you want to perform an action on each of the elements of an array.

Let’s start by looking at the definition of the map method as described on Mozilla Developer Network:

The map() method creates a new array with the results of calling a provided function on every element in this array.

Let’s understand this definition:

  • We will need an array, to run the map method on
  • We have to supply this method with a function
  • This function is called on every element in the array
  • And the output is a new array

Now that we know the definition let’s look at an example. We have an array of ten numbers, we want to multiply each of these numbers by 10 and lastly we want the result in a new array.

Here is how we achieve this using a For Loop:

We have achieved the required result and here is how we got to it:

  • Create a new array
  • Keep track of each element
  • Multiply each element by ten
  • Push result of multiplication into the new array

Another way to achieved this, would be by using a library like Lodash:

Simple and elegant solution but we have to use a library to achieve this. What if we can get the same result without using a library and without having to use a for loop!

Enters our friend, JavaScript’s very own map method, take a look:

Important notes about the map method :

  1. We are not writing something like this map(array, function). This is because map is defined on Array.prototype, so we call it on any array and it accepts a callback as its first argument.
  2. In the above code we are passing just one argument to the function, that is the current number. But we can pass a total of three argumets to this function:
    • Current item in the array
    • Array index of the current item
    • Entire array you called map on
  3. The return statement: If you forget the return statement, the map method will push one undefined for each element in the array. And you will have a new array full of undefined.

If you are using ES6(ES2015), you can also use the ‘fat arrow’:

Let’s have a look at a more practical example. We make an API call and it returns an array of objects. Something like this:

And we want to format the date in human readable form. Here is how we will do it.

Note, we are using the Moment.js library here to help us with date formatting.

That’s about it for this post.