Notes

Array.forEach()

Edit on GitHub

JavaScript

.forEach()

The forEach() array method accomplishes the same thing as regular for loops, but it does it asynchronously and in a simpler/easier way.

We have a stocks array, from which we just want the stock symbols.

1let stocks = [
2  { symbol: "APL", price: 693 },
3  { symbol: "HUBC", price: 103 },
4  { symbol: "POL", price: 413 }
5]

Here’s how you’d do it using a regular for loop.

 1function getStockSymbols(stocks) {
 2  let symbols = [],
 3      counter,
 4      stock
 5   
 6  // Regular for loop
 7  for (counter = 0; counter < stocks.length; counter++) {
 8    stock = stocks[counter]
 9    symbols.push(stock.symbol)
10  }
11  
12  return symbols
13}
14
15let symbols = getStockSymbols(stocks)
16
17console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]

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

 1function getStockSymbols(stocks) {
 2  let symbols = []
 3  
 4  // forEach loop
 5  stocks.forEach(stock => symbols.push(stock.symbol))
 6  
 7  return symbols
 8}
 9
10let symbols = getStockSymbols(stocks)
11
12console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]

Related