DEV Community

loading...
Cover image for What is .map() and how does it work

What is .map() and how does it work

Arsenii Gorushkin
Backend developer who wants to be Fullstack and DevOps Engineer
・2 min read

Have you ever wandered what is .map() function in Javascript? Then this tutorial is for you! Today we will look at how .map() works, and what does it do.

About .map()

In Javascript, map function is a method used on arrays, it cycles through every element and executes a callback on each iteration. After finishing iterating through elements, it returns a newly constructed array, that has been constructed according to values returned by callback functions, ran in each iteration.

How to use

map() method takes in 2 parameters

  • Callback Function
  • ThisArg (Value to use as this, in callback function)
array.map(callback, thisArg);
Enter fullscreen mode Exit fullscreen mode

As an argument, callback has 3 parameters

  • Current Element
  • Current Index
  • Current Array
array.map((element, index, array) => {});
Enter fullscreen mode Exit fullscreen mode

In today's example, we aren't going to be using Current Array and Index, we'll stay on Current Element.

Let's now look at how it works. Throughout each iteration, our callback function is execute, and returned by this very same function is an element which is pushed into an array that is returned to us at the end. Don't worry, you don't need to store array in anywhere through iterations, it is automatically stored in function memory. Let's now look at examples of the .map()
use.

EXAMPLE

const numberArray = [1, 2, 3, 4, 5];

const newArray = numberArray.map((x) => x * 2)
//newArray is [2, 4, 6, 8, 10];
Enter fullscreen mode Exit fullscreen mode

In the script above, as you can see, it make an array with all of the elements multiplied by 2, and then returns it to us. This is basically the whole functionality for .map().

Thanks for reading this post! If you found it helpful, then feel free to leave a reaction and or follow me, but if you didn't, then tell me what you didn't like and I will try to fix it in future.
Thank you all, and cya later!

My other posts

Discussion (0)