Please enable JavaScript to use CodeHS

Looping Through Arrays in JavaScript

Learn how to use for loops to access items in your arrays.

By Rachel Devaney

Arrays are great for storing data in a single variable (learn more about the basics of arrays here). We know that we can access each item by using the item’s index, but what if we want to go through our entire list? Let’s say we have a list that contains some numbers, and we want to determine which of the numbers in our list are even.

var nums = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];
Plain text

We could do something like this with a series of if statements (we can determine if a number is even by using the modulus operator):

if(num[0] % 2 == 0){
    print(num[0]);
}
if(num[1] % 2 == 0){
    print(num[1]);
}
if(num[2] % 2 == 0){
    print(num[2]);
}
...
Plain text

Whew, that’s a lot of typing. Wouldn’t it be nice if we could just loop through the array and apply the same if statement to each item? Lucky for us, we can!

Looping Through Arrays with For Loops

One way to loop through an array is to use a for loop. In order to use a for loop, we need to know the length of the array to determine how many times the for loop should repeat. We can do this using array.length, which returns the number of items in the array. We can find the length of the nums array like this:

var length = nums.length;   
print(length);         // prints 10 because there are 10 items in the nums array
Plain text

Now that we know how long our array is, we can use a for loop to loop over each item and apply the same code:

for(var i = 0; i < nums.length; i++){
    // code to apply to each item in the array
}
Plain text

Going back to our original plan, we could easily use a for loop to print out the even numbers - that’s way easier than writing 10 if statements!

for(var i = 0; i < nums.length; i++){
   var current = nums[i];     // gets the item at index i
    if(current % 2 == 0){     // asks if the number is divisible by 2
        println(nums[i]);     // if it is, print it out
    }
}
Plain text

for…of Loop

A for...of loop is another great tool we can use to loop over arrays. The cool thing about for...of loops is that they iterate over each element of the array instead of the indices. A for...of loop looks like this:

for(var variable of array){
    //code to apply to each element in the array 
}
Plain text

Using a for...of loop to print the even numbers in the nums array would like this:

for(var number of nums){
    if(number % 2 == 0){    
        println(number + " is even!");    
    }
}
Plain text

Similar to how we initialize the variable i in a standard for loop, we create the variable numbers in the for...of loop. (Note that we can name this variable anything we want.) Each loop stores the next element, or value in the nums array in the variable number. This enables us to use the variable number instead of nums[i] to access each individual element.

See these loops in action below, and explore with these guiding questions:

  • Try adding a few more even and odd numbers to the nums array. What happens?
  • Add an else statement to print out if the number is odd.
  • In the for...of loop, try changing the name of the variable number to num. What happens?
  • Which type of loop do you prefer?

Iterating with Math

If we have an array of numbers, iterating makes it easy to do some mathematical calculations, such as find the sum, average, product, minimum, and maximum. Let’s say we have an array that stores the temperatures of a perfect spring week:

var temps = [69, 70, 64, 60, 68, 70, 75];
Plain text

To find the average temperature (avg = sum/number of items), we create a variable to store the sum. Then, we loop over the array, adding each item of the array to the sum. Finally, to find the average, we just divide the sum by the length of the array! All together, it looks like this:

var sum = 0;                             // Creates a variable to store the sum
for(var i = 0; i < temps.length; i++){   // Loops over the array 
    sum += temps[i];                     // Adds each temperature to the sum variable
}
var average = sum/temps.length;          // Finds the average by dividing the sum by the number of days, which is the length of the array!
println(average);                        // prints out 68
JavaScript

Similarly, we can find the minimum and maximum of an array of numbers by creating a variable to store the minimum and maximum. Then, we can loop over the array to see if each item is less than or greater than the current minimum and maximum values. If the value is less, we can update the minimum variable and if the value is greater, we can update the maximum variable.

Check out the example below to see this in action! Note that the second loop uses a for...of loop to demonstrate that either type of loop will work. Can you add code to find the maximum temperature?


Your Turn!

Create an array to store the following set of game scores: 200, 145, 90, 84, 106, 213, 300, 214. Then, use loops to find and print the average game score, the highest game score, and the lowest game score. Try using both the standard for loop and the for...of loop. Which do you like better?


Iterating with Graphics

We can also iterate over arrays that store items other than numbers, such as graphics objects. Take a look at the program below. We first create an array of squares, squares. Then, we use a timer and the function blink to iterate over the array squares to change the color of each square to a random color every 100 milliseconds. If we didn’t have arrays, we’d have to update the color of each square individually!

Explore the example below!

  • Try changing the number of squares.
  • Try adding code to the blink function that changes the position of each square to a random position. (You can use Randomizer.nextInt(low, high) to get a random number, with low being the lowest value and high being the maximum value.)