Map function

Map

The .map() method is used when you want to 1. perform a set of statements with every value in the iterable and 2. return the (presumably) modified value.

Let’s use a simple example of calculating sales tax on an array of prices.

const prices = [19.99, 4.95, 25, 3.50];
let new_prices = [];for(let i=0; i < prices.length; i++) {
   new_prices.push(prices[i] * 1.06);
}

We can achieve the same results using .map():

const prices = [19.99, 4.95, 25, 3.50];let new_prices = prices.map(price => price * 1.06);

The syntax above is condensed so let’s walk through it a bit. The .map() method takes a callback, which can be thought of as a function. That’s what is between the parentheses.

The variable price is the name that will be used to identify each value. Since there’s only one input, we can omit the usual parentheses around the parameters.

The statement after the arrow => is the body of our callback. Since the body has only one statement, we can omit the curly braces as well as the return keyword.

Just in case this is still confusing, let’s write it out fully for reference:

const prices = [19.99, 4.95, 25, 3.50];let new_prices = prices.map((price) => {
   return price * 1.06
});

Leave a Comment