DEV Community


Posted on

Beginner’s guide to JavaScript’s map()

What is a map() function and how do we use it? Let’s use a Spongebob analogy to unpack what it does.

In this episode, Spongebob, Patrick, and Mr. Krabs go on an adventure to find the Dutchman’s treasure. The three rely on a map to get to their destination. This is a good start. A regular map outlines the terrain of the real world, gives us a copy of the features that exist, and we can arrive at different end points depending on the path we take. Our map() function takes on similar characteristics, hence, “map”().
W3schools defines a map() as

— a method that creates a new array with the results of calling a function for every array element

— a method calls the provided function once for each element in an array, in order.

— a method that does not change the original array.

Let’s delve into what this means using an example:

Image description

In the above example we have an array, “numOfKrabbyPatties”, that shows the amount of Krabby Patties we can imagine Mr. Krabs, Spongebob, and Patrick having at the beginning of their treasure hunt. Next, the variable, “leftoverPattiesArr”, is created to represent what happens to the Krabby Patties of each character after a certain amount of time. In this case 3 are eaten by each character.

If we take a look at the value of “leftoverPattiesArr” we can see that we are taking our “numOfKrabbyPatties” array and using the map() function on it. The map() function inherently calls on EACH item in the “numOfKrabbyPatties” array, but we need to tell it what we want it to do with the “numOfKrabbyPatties” array. This is where the function “hungryCharacters” play its role. It gives the map() some guidance. Just like our three characters traversing the ocean floor to find the “X” on the treasure map, our “hungryCharacters” function is similar in that it provides the trail the array must follow to get to its new end point.
Taking a closer look at our “hungryCharacters” function, one can notice that a parameter, “patties”, is set. Wrapping my head around what this parameter does was a little challenging at first. Alas, with the help of Spongebob and his friends, anything is possible! Remember that the function is called once for EVERY element in the array.

Image description

What is happing when we invoke “leftoverPattiesArr” is the map takes the first element in “numOfKrabbyPatties” and passes it through our function. In our case 12 Krabby Patties becomes the “patties” placeholders, and the subtraction (12–3) is performed. Again, the inherent property of the map() is to now take the second element of “numOfKrabbyPatties” and follow the same path. The second element is 6, therefore as it moves through the function it, for the time being, replaces the “patties” placeholders. Thus performing (6–3). The same process repeats for the last element in our array as well. Finally, we have a non-destructive process that keeps our old array, “numOfKrabbyPatties”, in tact while providing us with a new, manipulated array, “leftoverPattiesArr”.

As we navigate with our map, what gets altered is how we exist within that terrain. We are, in other words, making changes to our relationship with our map. One minute we are at point “a” and some time later we are at point “b”. Similarly, in our example the Krabby Patties are being manipulated as they move through their map() terrain. At the so called beginning, point “a”, of the map() they are one way and by the end, point “b”, another.

Let’s dig a little deeper!

We don’t always deal with arrays that are that simple. Let’s take a look at one with some objects inside. If you aren’t familiar with the Spongebob episode being referred to throughout this article, you should know that the three get into a small quarrel regarding the treasure after it’s found. Their commotion wakes the ghost of The Flying Dutchman and he is subsequently angry. For the purpose of this example, let’s say that he takes back his treasure chest and gives each of our characters 1 gold coin.

We want to express this by creating sentences with the new information we have. Below you will see “characters”, an array of 3 objects containing 2 key:value pairs. Our function “getTreasure” will be invoked for every object in our array. In this case 3. Similarly to our previous example, the parameter, “oneCharacter”, is a place holder for each entire object. For example, the first iteration would take {name : “Mr. Krabs”, treasure: 0} and pass it in as the new temporary placeholder. At this point, between the curly braces “{}”, is where we say what we want to do with this object. In this function we are saying we want ${}. “OneCharacter” being the placeholder for each object iteration within the array. We then want to grab the value of “name” to begin our sentence. This is interpolated using back-ticks at the beginning and end of the return statement. Then putting our variables between ${}. This allows us to incorporate stringed elements such as “has” and “piece of gold!”. We interpolate a second time using ${oneCharacter.treasure + 1}. Just like the previous interpolation, our “OneCharacter” is the placeholder for each iteration over the objects. We then grab ahold of the “treasure” key in order to get its value. Finally we add 1 to the value. As a final result one can see that gives us a new array of three different strings! Remember, our initial array of “characters” was not changed because map() is non-destructive.

Image description


Top comments (0)