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.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay