What is Map and How to Implement Your Own Map Method in Javascript

Michael Tong
Webtips
Published in
2 min readJul 17, 2020
What is Map and How to Implement Your Own Map Method in Javascript
Photo by Capturing the human heart. on Unsplash

You are probably thinking about the world map when you are looking into this picture.

Except today…we are talking about the map function in relationship.

What is the map function?

In javascript, the map function provides a convenient way to apply some function to every single element in an array.

For example, I can use a map function to multiply each element for a factor of 2:

Simple, right? You can also apply the same rule to strings:

Okay. simple right? How does it work behind the scene? How do we implement our own version of the map function?

Here is an example:

Here in the custom map function, we apply func(or callback, which ele => ele * 2) to every element and store the result into the array. “this” would be arr which calls customMap, its new prototype method.

In another word, a map function allows a function to each element in the old array and return a new array with all the new results.

Well..why should we use the map function when we can use the for loop to solve the same problem?

It’s simply more elegant. I can simply run a one liner to generate a new array instead of writing a for loop to modify an array like I did above.

As useful as the javascript map function is, there are scenarios where the map is not useful. If you are trying to utilize every element to perform some sort of action but do not want to generate a new array then the map function is probably not the one to use.

That’s it! You now understand how to write map function & using it properly.

--

--