JavaScript Array.map()

16 August 2022

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.

let cars = ['BMW', 'Jaguar', 'Lexus', 'Mercedes'];

for(let i=0; i<cars.length; i++) {
    console.log(cars[i]);
}

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.

let cars = ['BMW', 'Jaguar', 'Lexus', 'Mercedes'];

cars.map(car => {
    console.log(car);
});
Output
BMW
Jaguar
Lexus
Mercedes

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.

let numbers = [1, 2, 3, 4, 5];

numbers.map(number => {
    console.log(number * number);
});

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.

let numbers = [1, 2, 3, 4, 5];

numbers = numbers.map(number => {
    return number * number;
});

console.log(numbers);
Output
[1, 4, 9, 16, 25]

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.

let carDetails = [
    {make: "Ferrari", model: "F40"},
    {make: "Lamborghini", model: "Countach"},
    {make: "Aston Martin", model: "DB7"}
];

let cars = carDetails.map(car => {
    return car.make + ' ' + car.model;
});

console.log(cars);

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.

let numbers = [1,2,3];

numbers.map((element, index, array) => {
    console.log(element);
    console.log(index);
    console.log(array);
});
Output
1
0
[1, 2, 3]
2
1
[1, 2, 3]
3
2
[1, 2, 3]

The Array.map() function with these arguments allows us to manipulate the array in any way that needs it.