DEV Community

Cover image for what is array map() in JavaScript
Christopher Glikpo  ⭐
Christopher Glikpo ⭐

Posted on

2 2

what is array map() in JavaScript

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay