The Array forEach method

InstructorJafar Husain

Share this video with your friends

Send Tweet

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.

devin pastoor
~ 9 years ago

little typo in the transcript! haha,

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

Jack
~ 9 years ago

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);
}
abhinav reddy
~ 9 years ago

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

Charles
~ 8 years ago

ES6 code:


function getStockSymbols (stocks) {
  const symbols = []

  stocks.forEach(({symbol}) => symbols.push(symbol))
  return symbols
}