Array.map Explained

Sep 01, 2022 | O. Wolfson
javascript

In JavaScript, Array.map is a method that loops over items in an array and returns a new array.

const items = ["item1", "item2", "item3", "item4"];

items.map((item) => {
  return `The current item is: ${item}`;
});

Here above we have an array called items. It's populated with several strings representing items. We can use the Array.map method to loop over the strings.

The first parameter of map is a callback function that is invoked on each loop. The first parameter of the callback function is the value. I have named the value 'item'. The item value will hold the contents of the array at the specific iteration index, so 'item1' will be the first value, then 'item2', and so on.

Array.map is useful when we need to make a new array based on data in an existing array. In the example below, we will return a new string at each iteration.

const animals = ["cat", "dog", "fish", "bird"];
const kids = ["Billy", "Lisa", "Trevor", "Tracy"];
const favoriteAnimals = animals.map((animal, index) => {
  return `${kids[index]}'s favorite animal is ${animal}.`;
});

Let's create a new array called 'favoriteAnimals' by mapping an array called animals. We will return a string that include the description of each animal, and the name of a kid (from another array). Note that we've given our callback function a new parameter, index. Index will hold the iteration count for each loop: 0, 1, 2, etc. We can use the index to extract values from the kids array. The result will be a new array, below.

[
  "Billy's favorite animal is cat.",
  "Lisa's favorite animal is dog.",
  "Trevor's favorite animal is fish.",
  "Tracy's favorite animal is bird.",
];