Array.forEach()
.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.
let stocks = [
{ symbol: "APL", price: 693 },
{ symbol: "HUBC", price: 103 },
{ symbol: "POL", price: 413 }
]
Here’s how you’d do it using a regular for
loop.
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' ]