what is array map() in JavaScript

Christopher Glikpo ⭐ - Nov 16 '22 - - Dev Community

map() method creates a new array with the results of calling a function for every array element.

A function that is executed for every element in the array is passed into map() which has these parameters:

  • current element
  • the index of the current element
  • array that map() is being called on

An example of using map() would be to square every element in an array

let numbers = [2, 4, 6, 8, 10];

// function to return the square of a number
function square(number) {
  return number * number;
}

// apply square() function to each item of the numbers list
let square_numbers = numbers.map(square);
console.log(square_numbers);

// Output: [ 4, 16, 36, 64, 100 ]
Enter fullscreen mode Exit fullscreen mode

Another example is converting an array of data into JSX.

const food = [
    { id: 0, name: 'orange', color: 'orange' },
    { id: 1, name: 'banana', color: 'yellow' }
];

food.map(food => {
    return (
        <div key={food.id}>
            <div>
                {food.name} - {food.color}
            </div>
        </div>
    );
});

Enter fullscreen mode Exit fullscreen mode

summary of map()

Use map() when something needs to be done on every element in an array.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player