Array Map in JavaScript. A simple method made simpler

Subscribe to my newsletter and never miss my upcoming articles

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:

  1. It LOOPS over the array and has access to each item in the array in a callback function.
  2. We will CHANGE / MODIFY a specific or all of the items in the array
  3. 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 = {
  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 = => {
  return `${word}ed`;

But we can get rid of the return and the extra line and make it like this:

const pastWords = => `${word}ed`);

So we transformed the code from this:

var presentWords = ["work", "play", "click", "end", "start"];
var pastWords = {
  return word + "ed";

to this:

const presentWords = ["work", "play", "click", "end", "start"];
const pastWords = => `${word}ed`);

I also have a video on my channel about the

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

Rohil's photo

Congrats on your first blog post max 💛💛💜

Sunrit Jana's photo

GG Usman AKA Max! :P

Ivan Maximiliano Saldano's photo

Welcome to Hashnode Usman!

Usman Sabuwala's photo

Thanks! 🤩