DEV Community

Shahir Ahmed
Shahir Ahmed

Posted on

What is Array.map and How to Use It

While interning as a software engineer at AMEX, I've come to learn you can write the same line of code a thousand different ways, only ever so slightly more concise every time. Most of the time I can also find myself using a certain method without any regard as to how it is more beneficial to use than any other. One piece of code that I recognized became more often used in my arsenal is the Array.map method. I decided to take this opportunity to learn more about the method and share those thoughts.

What is it?

Array.map is a function that creates a new array by calling a function on each element in an array. Essentially, it's a loop in which the goal of that loop is to create a new array from a given array.

Imperative vs Declarative Programming

To understand Array.map and what it does, it helps to understand what imperative and declarative programming is. Imperative programming uses statements to mutate the state. Prior to using Array.map, I may have used a for loop to push items into a new array.

Imperative Programming

In this example I have an array of objects that contain some user data. Let's say my goal is to take this array of objects and convert it to an array of strings that only contain the usernames. I can approach this imperatively by creating a new empty array then use a for loop to push each individual username to a new array.
Screen Shot 2021-01-28 at 4.43.48 PM

Declarative Programming

Now if I want to approach this same piece of code declaratively, I can use the Array.map method. With Array.map, I can use a callback function to create a new array. A callback function is a function that will be called on later, which is why it has that name. Once it's gone over every item in the array, the map function will return an array containing the values returned from each call of the function. This is how I am then able to compute a new value and return it, giving us our array of strings.
Screen Shot 2021-01-28 at 4.49.53 PM

Conclusion

After this, you can see that Array.map gives us the same result, only with less code written - as is always the goal to keep your work more concise - and without mutating the original internal array, or source. I hope I will was able to deliver a nice and gentle introduction to Array.map. :)

Top comments (0)