We have already talked about how to handle some of loops types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how we can make a foreach loop in Javascript.
A foreach loop helps us in a simple way to go through the elements of an array. So the first thing we'll do is create our list of elements. In this case we have created a list of countries as follows:
const countries=['Italy','Spain','France','Holand','Germany','England','Greece','Ireland'];
Before moving on to foreach loops, let's remember that for traversing lists of elements we have seen that for-loops have a format more or less similar to the following:
for (initial_value;control;increment) {
// Rules
}
However, we have to get this structure out of our minds. And is that in the case of the foreach loop in Javascript this is a method of the Array object, not a loop to the use, with the following structure:
countries.forEach(function(item,index) { });
As we can see the method receives a callback function with two elements, on the one hand the item that will be the element on which it will iterate and on the other hand the index that it occupies in the list. In this way the code that we have inside the function will be executed for each of the elements that we have inside the list.
The function can be an anonymous function within the .forEach() method or we can define it and assign it to the method.
In this way, we could display the array elements on the screen with the forEach() method in the following way:
countries.forEach(function(item,index) {
console.log("The country" + item + "position is:" + index);
}
In this simple way we will have executed a foreach loop in Javascript.