DEV Community

Drew Womble
Drew Womble

Posted on

Using `.map()` in JavaScript

In JavaScript, the .map() function is a higher-order function that is used to transform an array by applying a function to each element of the array. The .map() function creates a new array with the results of calling the provided function on every element in the original array. It does not modify the original array.

The basic syntax for the .map() function is as follows:

array.map(function(currentValue, index, arr))
Enter fullscreen mode Exit fullscreen mode

The function() is required and will be the function that is run on each array element. currentValue is also required and represents the value of the current element. The index is optional and represents the index of the current element. arr is also optional and is the array of the current element.

.map() is an incredibly useful tool in JavaScript. You could use other methods such as for...of loops; however, .map() increases the readability of your code.

Here is an example of the differences between using a for...of loop and using the .map() function. Let's say we have the following array of menu items at a barbeque restaurant:

const menuItems = [
     {
          dish: 'Pulled Pork',
          price: 12.99
     },
     {
          dish: 'BBQ Chicken',
          price: 11.99
     },
     {
          dish: 'Brisket',
          price: 13.99
     }
 ]

Enter fullscreen mode Exit fullscreen mode

It's May 16th! International barbeque day! The owner calls and says that everything should be 50% off! We could use a for...of loop to iterate through the array and change the prices. Like so:

function loopAndUpdate(array, updater){
  const updatedArray = []
  for(let item of array){
      updatedArray.push(updater(item))
  }
  return updatedArray
}
function halfOff(item){
  item.price = item.price/2
  return item
}
console.log(loopAndUpdate(menuItems, halfOff))
//=> [
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
console.log(menuItems)
//=> [
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
Enter fullscreen mode Exit fullscreen mode

For this example we wrote a function that allows us to loop through our array and return the updated array. Then wrote another function to change the price to half off. Notice the original array was changed. If we wanted to prevent that we could use the Object.assign() function like so:

function halfOff(item){
  let itemCopy = Object.assign({}, item)
  itemCopy.price = itemCopy.price/2
  return itemCopy
}
console.log(loopAndUpdate(menuItems, halfOff))
//=>[
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
console.log(menuItems)
//=>[
  { dish: 'Pulled Pork', price: 12.99 },
  { dish: 'BBQ Chicken', price: 11.99 },
  { dish: 'Brisket', price: 13.99 }
]
Enter fullscreen mode Exit fullscreen mode

In this example the original object remains unchanged because we made a copy of it and passed that into our loopAndUpdate function. This works, but things are starting to get messy and overcomplicated. Especially when we have .map() at our disposal! Let's assume we are dealing with the same object as before menuItems. Here's an example using .map() to do the same thing:

const halfOff = menuItems.map(item =>{
  item.price = item.price/2
  return item
})
console.log(halfOff)
//=>[
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
console.log(menuItems)
//=>[
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
Enter fullscreen mode Exit fullscreen mode

That looks a lot better, but I know what you're thinking. "I thought .map() didn't change the original array!" While this is true JavaScript is not storing the actual object at each index of menuItems. It's storing a pointer that references the location in memory at where the object is stored. .map() is creating a new array, but it's filled with pointers to the same objects. To fix this we can use Object.assign() in the same way we did before:

const halfOff = menuItems.map(item =>{
  let itemCopy = Object.assign({}, item)
  itemCopy.price = itemCopy.price/2
  return itemCopy
})
console.log(halfOff)
//=>[
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
console.log(menuItems)
//=>[
  { dish: 'Pulled Pork', price: 12.99 },
  { dish: 'BBQ Chicken', price: 11.99 },
  { dish: 'Brisket', price: 13.99 }
]
Enter fullscreen mode Exit fullscreen mode

Fixed! Now .map() really shines when we already have a helper function to take 50% off the price:

function halfOff(item){
  let itemCopy = Object.assign({}, item)
  itemCopy.price = itemCopy.price/2
  return itemCopy
}
const halfPrice = menuItems.map(halfOff)
console.log(halfPrice)
//=>[
  { dish: 'Pulled Pork', price: 6.495 },
  { dish: 'BBQ Chicken', price: 5.995 },
  { dish: 'Brisket', price: 6.995 }
]
Enter fullscreen mode Exit fullscreen mode

All condensed into one line! .map() really is a useful function. Hopefully now you understand why it is useful, and understand how to use it. Not only does it make your code easier to read, but it makes things easier on you too!

Top comments (0)