DEV Community

harjas816
harjas816

Posted on

What is .map() ?

What are methods

Methods are certain functions meant to be used for specific, repeatable purposes in your code. For instance, instead of having to write your own function that makes a string's letters all uppercase repeatedly, you can just call this Javascript method called .toUpperCase() to do it for you every time you need to.

String.toUpperCase()
Enter fullscreen mode Exit fullscreen mode

One of these methods, and arguably one of the most useful of them ,is called .map(). In order to understand .map() though, we need to understand what a Javascript array is first.

What is an array ?

An array is an iterable group of items kept inside of a pair of square brackets

const my_array = [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Arrays are probably the most common type of data structure that programmers come across. If we're going to be dealing with large amounts f data, we would like the ability to organize them into groups that we can reference and manipulate. Thankfully, .map() allows us to do just that!

When we call the .map() function, we give it a callback function as an argument. This is a function that is going to take all of the items in the array as an argument, one at a time, until the function has gone through the entire array.

const mapped_array = my_array.map(arrayItem => {console.log(arrayItem})
Enter fullscreen mode Exit fullscreen mode

With this code, it would print the numbers 1-5 in the console, and would also console.log anything we decide to put in the array afterwards.

(result)
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Now that you know what .map() is, you are prepared to expand your ability to manipulate arrays in order to solve more complex problems than you could before. Good Luck!

Top comments (0)