DEV Community

Cover image for Meet .map() the Invaluable JavaScript Array Method
Todd Carlson
Todd Carlson

Posted on • Edited on

Meet .map() the Invaluable JavaScript Array Method

There are several ways one can iterate over data with JavaScript. The tried and true for loop, .forEach(), .filter(), etc. However, depending on what you need to accomplish, I have found the .map() method to be especially useful, and it is one I return to again and again. If you need to iterate over an array of data, transform its elements, and return a new array, .map() should be your go to method.

Alt Text

In the above example we have an array of numbers, and for each number in the array we would like to increment that number by ten.

Using the .map() method all we have to do is return the value of each number and add ten to it. The .map() method will return a new array with new values, leaving the values in the original array unchanged.

One extremely important detail is that the .map() method always takes a function definition as its first parameter. As seen in the above code example, the function has three arguments available to it. These arguments are called for each element in the array, and the return values that the function creates will become the data inside the new array.

I hope this explanation of .map() has been helpful. I find myself using .map() all the time in my own projects, especially as I've been diving deeper into JavaScript and React. Happy coding!

Top comments (0)