Array is a list or collection of items and one of the benefits of using array over a lot of variables is to be able to find or list items. We will look at some of the basic and easiest ways of iterate over an array. There are many methods build into the array to help programmers search and filter the array, but right now we will focus on the basics.
First we will look at the for loop for iterating over an array. The for loop is described on this page, so take a look at it if you need to refresh your skills.
​
When using a for loop on arrays we use the length of the array as part of the condition. In the code we want to run we use the counters current value to access the item in the array.
The for loop shown above is going over all of the items in the array and prints them out. It does just the same as you are used to with a for loop. But since we are now iterating over an array of items we have some other options when it comes to the for loop. The array opens up the option to use something called a for in loop and a for of loop that we will look closer at now.
​
The for in loop is a very easy way of iterating over an array. It's syntax is shorter and simpler as it gives us the key (or index if you like) as part of the loop structure.
Just like the for loop, the for in loop will list out the items in the array.
​
Now let's look at the for of loop. This loop is again different in the way that it gives us the item in the list as part of the loop structure.
Again it's listing out the items in the array. So as you can see it is a few ways you can use a for loop on an array. Which is best is up to you to decide.
​
At last we will look at the forEach() method that we can use to loop through an array with. The array method forEach() will loop through the array it's used on and execute the code you provide for each item in the array. This method can be used as a simple loop as we will show you now, but can also be very advanced and do a lot more.
On this page we have looked at different ways of looping through an array. It's now up to you to learn them and determine which you prefer. Which do you like, which is easier to write and read.