1. Using for loop

for() loop is the most common way of iterating a collection in most programming languages. Here is an example of for() loop for iterating a collection in javascript.

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for(let i = 0; i < days.length; i++) {
	console.log(days[i]);
}

Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

2.Using forEach method

forEach() is a member of the array prototype and uses a callback function for you to provide any custom logic to the iteration.

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
days.forEach(function(value, index) {
  console.log(value + "--" + index)
})

Output:

Monday--0
Tuesday--1
Wednesday--2
Thursday--3
Friday--4
Saturday--5
Sunday--6

3. Using enhanced for loop

Enhanced for loop is way better in iterating a collection when compared to the old for() and forEach() loops method of iteration. Let's iterate the same list using the enhanced for loop:

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for(const day of days) {
        console.log(day);
}

Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

This code produces the same result but it much better than the old for loop.

4. Getting the index in enhanced for loop

In the old for() and forEach() loops we have an index variable to keep track of the index of the collection we were iterating, but how do we get index in the enhanced for() loop. 

entries() of arrays gives as the index as well as the value of that index.

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (const day of days.entries()) {
  console.log(day);
}

Output:

[ 0, "Monday" ]
[ 1, "Tuesday" ]
[ 2, "Wednesday" ]
[ 3, "Thursday" ]
[ 4, "Friday" ]
[ 5, "Saturday" ]
[ 6, "Sunday" ]

We can also format the way the for method prints the index and its corresponding values by using a facility to "destructure arrays".

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (const [i, day] of days.entries()) {
  console.log(i + " -- " + day);
}

Output:

0 -- Monday
1 -- Tuesday
2 -- Wednesday
3 -- Thursday
4 -- Friday
5 -- Saturday
6 -- Sunday

5. Conclusion

In this article, we saw different ways of iterating the elements of an array in javascript. However, there are other ways of iterating the array that are also present we covered only a few of them.