Array.map()

.map()

transforms an array by performing a function on every item in the array, and returns a new array.

  • async: can work on data that arrives async over time
  • returns: A new array with each element being the result of the callback function.

We like working with map() because it works on data arriving asynchronously, unlike for loops where you can only work on synchronous data stored locally.

Here’s an array of stocks.

let stocks = [
  { symbol: "APL", price: 693 },
  { symbol: "HUBC", price: 103 },
  { symbol: "POL", price: 413 }
]

We want to get a new array with only the stock symbols. Here’s how we do it with .map()

function getStockSymbols(stocks) {
  return stocks.map(stock => stock.symbol)
}

let symbols = getStockSymbols(stocks)

console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]

Here’s how we’d do it traditionally with regular for loops.

function getStockSymbols(stocks) {
  let symbols = [],
      counter,
      stock
   
  // Regular for loop
  for (counter = 0; counter < stocks.length; counter++) {
    stock = stocks[counter]
    symbols.push(stock.symbol)
  }
  
  return symbols
}

let symbols = getStockSymbols(stocks)

console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]

And here’s how you’d do it with a forEach loop

function getStockSymbols(stocks) {
  let symbols = []
  
  // forEach loop
  stocks.forEach(stock => symbols.push(stock.symbol))
  
  return symbols
}

let symbols = getStockSymbols(stocks)

console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]

As you can see, map is superior to both for and forEach.. it’s a higher-order function (word-play intended).