Mastering the map() Method in JavaScript: A Practical Application.
Tags: javascript, webdev, tutorial, beginners
Published: 2024-02-27 09:57:37

In this short tutorial, we will learn how the `map()`method works and we will use it to map an array of products to produce a grid like this:
![Products Grid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zdbdnv1y8b9ins6p6sg.png)

The `map() `method is one of JavaScript's most commonly used methods. When applied to an array, the map() method will apply a callback function to every element in the array.

The syntax for the `map()` function looks like this:

```js
Array.map(function(element, index,array){
    // return something
)
```

The callback function takes the following parameters:

- element: the current element being worked on.
- index: the index of the current element . (this parameter is optional)
- array- the array the map() method is being applied to .(this parameter is optional)

Let’s start with a simple example: suppose you have a list of names, and you want to capitalize all the names.

```js
const names = ['antonio','melvin','sarah', 'john']
```
Using the `map()` method, let's first define the function which will take each element as a parameter and return a capitalized name.

```js
function capitalize(name){
     return name.toUpperCase()
  }
```
`toUppercase()` is a built-in JavaScript String method used to convert strings to uppercase.

Once we have defined the function, we will assign the result to a variable and then use the `map()` function to apply the capitalize function to each element of the names array.

```js
const capitalizedNames = names.map(capitalize )
console.log(capitalizedNames)
```
Rather than defining the callback function separately, you can combine everything and make your code more readable.

```js
const capitalizedNames = names.map(function(name,index, array){
            console.log(index)
            console.log(array)
            return name.toUpperCase()
        })
console.log(capitalizedNames)
```

The output will look like this,

![map()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58eedyi5qh1qeevx3mr4.png)

As you can see, even though we are not using the index and the array parameters, we still have access to them and can use them if we want to. If you are not using the index or the array, you can omit them from the code.

The syntax will be even shorter if you use an arrow function.

```js
const capitalizedNames = names.map((name) =>name.toUpperCase())
```

## Practical Example
Let’s look at a practical example that you can apply to your projects. Suppose we have an array of products, as shown below.

```js
let products = [
  {
    id: 1,
    description: "Cocktail Juice",
    price: 10.99,
    imageSrc: "https://source.unsplash.com/yIE7pZUmT_s"
  },
  {
    id: 2,
    description: "Pomegranate  juice",
    price: 20.49,
    imageSrc: "https://source.unsplash.com/IKaFDABbfFY"
  },
  {
    id: 3,
    description: "Passion Juice",
    price: 15.79,
    imageSrc: "https://source.unsplash.com/KUT4HK3-Z5s"
  },
  {
    id: 3,
    description: "Mixed Juice",
    price: 15.79,
    imageSrc: "https://source.unsplash.com/ktMU5IS407s"
  }
];
```
The array contains objects representing product properties and values. Each product has an ID, title, price, and image source.

We are tasked to display the products on a web page in a grid-like format.

Create a products div as shown below in your **index.html** page.

```html
<div class="products">
   <div class="card">
      <img src="https://source.unsplash.com/yIE7pZUmT_s" alt="" />
      <p>Cocktail Juice</p>
      <span>$ 20.50</span>
   </div>  
</div>
```
We will dynamically replace all the contents of the card with JavaScript.

Next, lets select the DOM element with the class name products.

```js
const productsCard = document.querySelector(".products");
```
Next, we want to iterate through the array of products and, for each product, generate a card containing all the product details.

```js
const productList = products
        .map((product,index) => {
           
          return `<div class="card">
            <img src="${product.imageSrc}" 
                  data-id = ${product.id}     
                  alt="${product.description}">
            <p>${product.description}</p>
            <span> $ ${product.price}</span></div>`;
        })
        .join("");

```

Lastly, we will append the generated HTML to the products container.

```js
productsCard.innerHTML = `${productList}`;
```

Here is the final result.


![products grid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fibwummvj027705ubshv.png)

Check out the [final demo on Code pen](https://codepen.io/Esther-k/pen/wvOLaOM). You can fork it and make improvements.

## Summary
The next time you reach for a for loop to iterate over an array, consider whether the `map()` method might offer a more efficient and elegant solution. Using the` map()` method:

- leads to more concise code,
- encourages a functional programming style.
- Enhances code readability

Thanks for reading

The best way to master JavaScript is by building projects. [Subscribe to the Practical JavaScript Newsletter](https://practicaljavascript.substack.com/) and level up your JavaScript skills.