Image Image Image Image Image
Scroll to Top

To Top

JavaScript

01

Jan
2017

No Comments

In JavaScript

By Manny

What is a forEach method

On 01, Jan 2017 | No Comments | In JavaScript | By Manny

The forEach method is a special kind helper method available to us on an array.  It helps us loop/iterate over an array. It is an alternative method to iterating over an array using a for loop.

for loop

var cars = [ 'Lambourgini', 'Porsche', 'Ferrari', 'Mazarati'];

for (var i = 0; i < cars.length; i++) {
  console.log(cars[i]);
}

forEach

var cars = [ 'Lambourgini', 'Porsche', 'Ferrari', 'Mazarati'];

cars.forEach(function(car){
  console.log(car);
});

When we call the forEach method we pass it an anonymous function, this is that internal argument. This function gets called one time for element in the cars array. This function can also be called the iterator function. In this example it will get called four times.

We can also extract the anonymous function to a listCars function that will later be passed in as an argument to the forEach method.

var cars = [ 'Lambourgini', 'Porsche', 'Ferrari', 'Mazarati'];

function listCars(car){
  console.log(car);
}

cars.forEach(listCars);