DEV Community

Cover image for Mastering the map() Method in JavaScript: A Practical Application.
vaatiesther
vaatiesther

Posted on • Originally published at javascript.plainenglish.io

Mastering the map() Method in JavaScript: A Practical Application.

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

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:

Array.map(function(element, index,array){
    // return something
)
Enter fullscreen mode Exit fullscreen mode

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.

const names = ['antonio','melvin','sarah', 'john']
Enter fullscreen mode Exit fullscreen mode

Using the map() method, let's first define the function which will take each element as a parameter and return a capitalized name.

function capitalize(name){
     return name.toUpperCase()
  }
Enter fullscreen mode Exit fullscreen mode

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.

const capitalizedNames = names.map(capitalize )
console.log(capitalizedNames)
Enter fullscreen mode Exit fullscreen mode

Rather than defining the callback function separately, you can combine everything and make your code more readable.

const capitalizedNames = names.map(function(name,index, array){
            console.log(index)
            console.log(array)
            return name.toUpperCase()
        })
console.log(capitalizedNames)
Enter fullscreen mode Exit fullscreen mode

The output will look like this,

map()

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.

const capitalizedNames = names.map((name) =>name.toUpperCase())
Enter fullscreen mode Exit fullscreen mode

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.

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"
  }
];
Enter fullscreen mode Exit fullscreen mode

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.

<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>
Enter fullscreen mode Exit fullscreen mode

We will dynamically replace all the contents of the card with JavaScript.

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

const productsCard = document.querySelector(".products");
Enter fullscreen mode Exit fullscreen mode

Next, we want to iterate through the array of products and, for each product, generate a card containing all the product details.

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("");

Enter fullscreen mode Exit fullscreen mode

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

productsCard.innerHTML = `${productList}`;
Enter fullscreen mode Exit fullscreen mode

Here is the final result.

products grid

Check out the final demo on Code pen. 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 themap() 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 and level up your JavaScript skills.

Top comments (0)