Coding for Kids

Arrays: Looping Through Arrays

One of the major uses of a for loop is to loop through all the elements of an array. You can read about the basic syntax of a for loop here.

Arrays are lists of things and they are indexed starting at zero 0. The last element in an array is one less than the length of the array. So, if an array has 10 things in it, the last index is 9 (not 10) because we start counting from zero 0.

Example:

Let's make an array and then use a for loop to run through it.

See this in repl.it

This will display all the colors in the same order they appear in the array. The really nice part is that you don’t need to know how long the array is. Let's say the array is declared somewhere else in your code and there was a way for the computer or a user to add to it to remove from it. When it gets to the loop, it will still work and show you whatever is there.

Check out this: let color = colorArray[i]; Do you know what this is doing? (Check out the Arrays section if you need help.) This takes the value of i and finds that index of the colorArray. So if i is 3, then it pulls colorArray[3], which is "silver" (not "gold" because the indexes starts at zero 0). Each time through, i increases and so it pulls the next element in the array.

By the way, we didn't even need to use the color variable. We could just put colorArray[i] into the console.log(); method directly, but this way makes the code more readable. Otherwise it would be: console.log(colorsArray[i]);

Array forEach() method

Arrays have a lot of their own methods that make life easier, many of which are discussed here. Because we are talking about looping through arrays here, I thought I'd mention this here too.

You can use the array.forEach() method to do something with every element in an array. It looks like this.

Syntax:

Example:

Above we looped through the colorArray to display each color. Here's how we could do the same thing with the .forEach() method.

See this in repl.it

So which is better?

Is using a for loop or the .forEach() method better for looping through an array?

There's some debate about it. The main support for the array method (.forEach()) is that it makes the code easier to interpret by a programmer. You immediately know the intent is to loop through all the array items. You can also shorten the code because each array element is automatically given to you and you don't need to use the index to find it, like in colorsArray[i].

However, older browsers may not support the array method, but they all support for loops. Also, you can break out of a for loop to end it early if you need to, but you can't do that with the array method.

In short, it mostly comes down to a matter of personal preference.

For each, a great day!

—Dr. Wolf