The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

The Array forEach method

The Array forEach method

4:03
Most JavaScript developers are familiar with the for loop. One of the most common uses of the for loop is to iterate through the items in an array. In this lesson, we will learn how to replace the for loop with the Array's forEach method - and shorten your code in the process.
Watch this lesson now
Avatar
egghead.io

Most JavaScript developers are familiar with the for loop. One of the most common uses of the for loop is to iterate through the items in an array. In this lesson, we will learn how to replace the for loop with the Array's forEach method - and shorten your code in the process.

Avatar
Dick

Is forEach a standard Javascript implementation? What about the performance compared to for()?

In reply to egghead.io
Avatar
Jafar

Performance is worse - but that's not the point. The goal is to teach you to program without loops, because loops don't work on async functions. We start with Arrays because JS developers are familiar with them. Soon we'll switch from Arrays to Asynchronous data steams where these functions must be used because loops don't work.

In reply to Dick
Avatar
devin

little typo in the transcript! haha,

Well, most jobs grifter developers are familiar with the "for" loop,

Avatar
Jack

In the for loop, why did you create an extra variable "stock" when we could have done the same with just the counter and the result array.
e.g.

var arr = [
    {symbol:"XFX", price: 240, volume:2333},
    {symbol:"TNZ", price: 332, volume:234},
    {symbol:"JXL", price: 120, volume:5345}
];

var result = [];
for(var i = 0; i<arr.length; i++){
 result.push(arr[i].symbol);
}
Avatar
abhinav reddy

If the foreach is asynchronous , is there a possibility for the function to return before the foreach has finished its execution...

Avatar
Charles

ES6 code:

function getStockSymbols (stocks) {
  const symbols = []

  stocks.forEach(({symbol}) => symbols.push(symbol))
  return symbols
}
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?