The Map Function in JavaScript

Hi guys !.

In this post we will learn how to use the Map Function in JavaScript. This particular function is very useful because not only can you map an array of objects, but also map elements.


What is map() ?

In simple terms, the map function calls a function once for each element in an array. Basically, it iterates over each element or item in an array and creates a new array based on what is returned by the function.

What is it used for?

It is commonly used when you want to take an array, make some changes on the items or apply a function on it, and get a new array. The basic syntax is :

map((element, index, array) => {
   //return something
})

Example 1

Let's look at the example below. We have a simple array that we are going to display on the console.

const array = [3,1,15,1,5,3,23]
//map the array
array.map((el) =>{
    console.log(el)
})

We are using ES6 arrow functions instead of the traditional return function. This will give the following output:

Example 1

Example 2

Now let's look at a more useful example. Here we have an array of objects, and we want to return only the names.

const users = [
  { firstName: "john", lastName: "doe" },
  { firstName: "Daniel", lastName: "steve" },
  { firstName: "mike", lastName: "hoff" },
];
//map the array and display only first names
users.map((el) => {
  console.log(el.firstName);
});

This will give the following result:

Example 2

Mapping and Array to Elements

The most useful application of the map function is when you want to display HTML elements using an array. In this case, we have an array of objects containing some user information and we want to display a the content as a list We will create an empty unordered list so that we can append the items to it.

<ul>
</ul>

Here we will map over the array and display the names as a list.

const users = [
  {
    name: "James",
    age: "17",
  },
  {
    name: "Ali",
    age: "19",
  },
  {
    name: "John",
    age: "21",
  },
];
//get the list
var list = document.querySelector("ul");

//display the names as a list
list.innerHTML = users
  .map((el) => {
    return "<li>" + el.name + "</li>";
  })
  .join("");

The join() method returns a new string by concatenating all of the elements in an array.

Your output will be : List


Check out my recent hubpages tutorial.

Thank you for Reading!