JavaScript Array .map() method

The JavaScript array .map() method loops through an array of items and returns another array based on the changes done on each array item inside the method.

The array.map() method is used change or tweak the items of the reference array and it's a good practice that you need to return another array out of it. Otherwise, you can use a regular for loop or forEach loop because these loops, by default, does not return an array.

This array.map() built-in JavaScript function accepts a callback function that we can use to get every item on each iteration of the array.

The callback function contains the current iterated item, the current index and the copy of the array itself on each iteration.

Array .map() Method Syntax

This is how you can use the the .map() method.


  array.map((item, index, array) => {
    // run your test here and make sure to return something
  })

Array .map() Method on Array of Objects


  const members = [
    { firstName: "Luffy", lastName: "Dragon" },
    { firstName: "Zoro", lastName: "Marimo" },
    { firstName: "Nami", lastName : "Swan" },
  ];

  const fullNames = members.map((member) => {
    return `${member.firstName} ${member.lastName}`;
  });

  console.table(fullNames);

For this example, we have an array of objects called members. Each member object has an attribute of firstName and lastName.

Say for example, We want to create another array that contains the full names of each member because we want to display the full names in the UI as a list or something.

To do that, we just have to use array map method by declaring members.map() based on the given syntax as discussed above. Then, we'll just interpolate the firstName and lastName. We'll make sure to return it otherwise our new array would contain same array length but with undefined value.

The output of our code above should be like this:


  [
    "Luffy Dragon",
    "Zoro Marimo",
    "Nami Swan"
  ]

Watch Tutorial

Here's a quick video tutorial about the JavaScript array .map() method.