JavaScript Array.map()
The JavaScript Array.map()
function allows you to easily loop over the items of an array without having to create your own loop. This can make your code more readable and easier to maintain.
Iterating an array with a loop
To understand how Arrap.map() works, let’s first create a simple array and show how we’d iterate through it using a traditional for
loop.
This works perfectly fine, but the parameters of the loop aren’t very readable and it gets more complicated if we want to start modifying the array data as we iterate over it.
Using Array.map()
Let’s see how we can use the .map()
function to loop through the same array and print each item to the console.
Using the Array.map()
function makes the code more readable but it also uses the initial array differently. In the for loop we’re accessing the cars
array directly, whereas the .map()
takes a copy of the cars
array to use within the function.
If we change the array we’re looping through to numbers, we can easily do some manipulation of the items in the array. In this example we’ll print to the console the square of each number in the array.
But what if we want to change the values in the original numbers array? The .map() function allows us return the copy of the array that we can assign to the original array or to a brand new one.
The return function becomes more useful when we’re working with complex multi-dimensional arrays. If we have an array of objects with multiple values, using .map() we can easily consolidate them into a single array.
There are two other arguments that can be passed into the Array.map()
function – index
and array
.
The index
argument gives us the index of the current element in the array, and the array
argument gives us access to the complete array that Array.map()
has been called on.
The Array.map() function with these arguments allows us to manipulate the array in any way that needs it.